Using JSON.stringify on [object Object] gives "[object Object]" on React - node.js

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.

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

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

Related

Passing Multiple parameters as catch them

I'm trying to pass 'slug' in the URL by adding 'id' and 'type'.
Code:
`/${category.slug}?cid=${category._id}&type=${category.type}`
<Route path="/:slug" element={<ProductListPage />} />
URL
http://localhost:3000/Samsung-3whQlbAYpm?cid=61ed050cab3efd275d49efd6&type=store
Problem : However, in the useParam() I received only slug not addition parameters such as 'cid' and 'type'
For example,
let params = useParams();
Its params have only 'slug' value which is 'Samsung-3whQlbAYpm'
How can I get addition value ?
The useParams hook only gets you the defined route params from the path part of the URL. If you want to access the queryString then use the useSearchParams hook from react-router-dom.
const [searchParams] = useSearchParams();
const cid = searchParams.get("cid");
const type = searchParams.get("type");
If you happen to still be using react-router-dom v5 then use the location object to get the search string to be passed to a URLSearchParams constructor.
const { search } = useLocation();
const searchParams = new URLSearchParams(search);

How to print the object value which return type is [Object , Object] in Nod JS?

below is one piece of code where i have to compare one object stored value (i.e 'resort') with the value compare that value what i am getting from the JSON file .
code -
resort = _.find(this.resorts.entries, (o) => {
return o.gqe_name === resort;
})
;
i have tried to get the value but the it is displaying as [Object,Object ] , tried with console .log('resort'+ resort) and log.info ('resort'+ resort).
is there any way i can view the return value ?
how i can print json stored value 'o.gqe_name' ?
JSON.stringify can help
const object = { test: { test2: 'value' } }
const result = JSON.stringify(object)
const result2 = JSON.stringify(object, null, 2)
console.log(result)
console.log(result2)

Having trouble grabbing data from MongoDB and using in new var (Next.js project)

Error I'm getting is this:
TypeError: Cannot read property 'latitude' of undefined
Here's the piece that's messing me up
const [user] = useCurrentUser();
var location = [user.latitude, user.longitude];
useCurrentUser() is here:
export function useCurrentUser() {
const { data, mutate } = useSWR('/api/user', fetcher);
const user = data?.user;
return [user, { mutate }];
}
I'm assuming I'm just calling it early, because it hasn't had a chance to go through the useCurrentUser() function yet. However, I can't for the life of me figure out how to call it when that's done?
edit:
It's also not usable later on in a component:
This works:
<span className="bold">{user ? user.latitude : ''}</span>
This doesn't:
<Map location={[user.longitude, user.latitude]}/>
What am I not understanding, hahaha

How can i simplify checking if a value exist in Json doc

Here is my scenario, i am parsing via javascript a webpage and then post the result to an restApi to store the json in a db. The code works fine as long as all fields i defined in my script are send. Problem is over time they website might change names for fields and that would cause my code to crash.
Originally i used code like this
const mySchool = new mls.School();
mySchool.highSchoolDistrict = data["HIGH SCHOOL DISTRICT"].trim();
mySchool.elementary = data.ELEMENTARY.trim();
mySchool.elementaryOther = data["ELEMENTARY OTHER"].trim();
mySchool.middleJrHigh = data["MIDDLE/JR HIGH"].trim();
mySchool.middleJrHighOther = data["MIDDLE/JR HIGH OTHER"].trim();
mySchool.highSchool = data["HIGH SCHOOL"].trim();
mySchool.highSchoolOther = data["HIGH SCHOOL OTHER"].trim();
newListing.school = mySchool;
but when the element does not exist it complains about that it can not use trim of undefined. So to fix this i came up with this
if (data["PATIO/PORCH"]) {
newExterior.patioPorch = data["PATIO/PORCH"].trim();
}
this works but i am wondering if there is a more global approach then to go and check each field if it is defined ?
You could leverage a sort of helper function to check first if the item is undefined, and if not, return a trim()-ed version of the string.
var data = Array();
data["HIGH SCHOOL DISTRICT"] = " 123 ";
function trimString(inputStr) {
return (inputStr != undefined && typeof inputStr == "string") ? inputStr.trim() : undefined;
}
console.log(trimString(data["HIGH SCHOOL DISTRICT"]));
console.log(trimString(data["ELEMENTARY OTHER"]));

Convert the object into a string and bring in the necessary form

An object comes to me. I write the variable key and the value through the loop:
let update_info = [];
for (let[key, value] of Object.entries(req.body)) {
update_info.push(`${key} = ${value}`);
}
console.log(JSON.parse(update_info));
Output to console:
undefined:1
user_name = name,user_email = #email.com,user_password = 12345678,about = aboutaboutaboutabout
^
SyntaxError: Unexpected token u in JSON at position 0
Why it happens?
I need to be displayed in the console like this:
'user_name' = 'name','user_email' = '#email.com','user_password' = '12345678','about' = 'aboutaboutaboutabout
How do i implement this?
I've reproduced your code like this and all you need to do is
JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string.
JSON.parse turns a string of JSON text into a JavaScript object.
let obj = {
"welcome": "hello",
"reply": "hi"
}
let update_info = [];
for (let[key, value] of Object.entries(obj)) {
update_info.push(`${key} = ${value}`);
}
console.log(JSON.stringify(update_info));
Try the below code:
You need not to parse it using JSON.parse because the array is not yet stringified, so you should use toString() to achieve the desired result
let update_info = [];
for (let[key, value] of Object.entries(req.body)) {
update_info.push(`'${key}' = '${value}'`);
}
console.log(update_info.toString());
If you are interested in printing the Object key value pair in the console to have better view use
console.log(JSON.stringify(object, undefined, 2))
This will print the object in proper format indented by 2 spaces

Resources