I am trying to pass an object data from one page to another. I have a line of code that can pass id and I tried to use it to pass object rather than an integer id but I can't get it right.
The code for passing id from source page:
const navigate = useNavigate();
id && navigate(generatePath("/employeelistedit/:id", { id })); //sample code which works fine when used
The code for passing the object data from source page copying the format of the code above:
function sourcePage(){
const navigate = useNavigate();
var values = {id: "someData", startd: "someData", endd: "someData"}
values && navigate(generatePath("/harvestcalendarmonitoring/:values", { values }));
} //with useNavigate and generatePath
This is the code in another page which receives the data:
const { values } = useParams(); //values gives [object Object]
const x = JSON.stringify(JSON.stringify(values)) //gives "[object Object]"
const y = Object.prototype.toString.call(values) //gives [object String]
For my routing, this is how I wrote it:
<Route path="/harvestcalendarmonitoring/:values" element={< Harvestcalendarmonitoring />} /> //refers to the receiving page
I know I'm not doing it right cause I know that "[object Object]" is showing that something is wrong somewhere in my codes. Any help and suggestions would be really much appreciated. Thank you in advance.
CodePudding user response:
It looks like you missed the stringify step:
function sourcePage(){
const navigate = useNavigate();
var values = JSON.stringify({id: "someData", startd: "someData", endd: "someData"});
values && navigate(generatePath("/harvestcalendarmonitoring/:values", { values }));
} //with useNavigate and generatePath
However, make sure generatePath
is also URL encoding this string values
or else you will likely have an invalid URL.
When it comes time to parsing the string back into an object, be sure to call JSON.parse
CodePudding user response:
With the help of Steve through his comment above/below this comment, use JSON.stringify() for the object before passing and receive it using JSON.parse().
Code in source page:
values = JSON.stringify(values);
values && navigate(generatePath("/harvestcalendarmonitoring/:values", { values }));
Code in receiving page:
const {values} = useParams();
const w = JSON.parse(values) //the w variable gives the desired and/or expected object data