In the app I am making, now a multipage app , there are two linked pages:
On the first page you can choose the access codes you want to add to your access card. These access codes have dates attached to them: an access code works between a start date and an end date. These dates can be edited on this page.
On the second page there is an overview of the chosen access codes. The dates chosen before are shown here and cannot be edited anymore.
The data for these tables comes from an external API and thus I cannot temporarily store those dates there. I dont feel like there is a more elegant solution than sending this information over url.
My idea to solve this issue was to make an array with the changed dates, encode this array with base64 and give it to the next page through url parameters. The array of objects is encoded and decoded using btoa() and atob().
The issue is now, when I encode it and decode it on the next page, it comes up as [object Object],[object Object] and not the actual object saved in it. The array being encoded looks something like: [{"id": 0, "name": accessToParking"}, {"id":1, "name": accessToShow}]
Does anyone know why this is the case or how I can fix it?
To maintain the structure of your data, you need to stringify your array before encoding and then parse it after decoding.
Encoding on the First Page
Convert your array to a JSON string before encoding it:
const dataArray = [
{ "id": 0, "name": "accessToParking" },
{ "id": 1, "name": "accessToShow" }
];
const jsonString = JSON.stringify(dataArray); // Converts array to a JSON string
const encodedData = btoa(jsonString); // Encodes the JSON string to base64
You can now safely pass encodedData as a URL parameter.
Decoding on the Second Page
When retrieving the parameter, decode and parse it back into an array of objects:
const encodedData = getParameterByName('yourParamName'); // Extracts the parameter from the URL
const jsonString = atob(encodedData); // Decodes the base64 string to JSON
const dataArray = JSON.parse(jsonString); // Parses the JSON string back to an array of objects
I think what has been suggested should be a pretty solid solution for you, but I am curious if you can use formatDataAsArray on your [object Object] data without needing to change the rest.
If I try that, I get an array of each character seperately still saying [{Object:object}]. The solution checked on this post was the thing that actually made it work. Still thank you for an alternative option!