I am working on react. I have an api that is using POST method, body contains sessionId
and returns response data in json. In postman, it’s working fine. But in React, its returning [object Object]
. Method is post, but api is getting the data. Please let me know what’s the issue why console.log("json " + json)
is giving [object Object]
const App = () => {
const [userInfo, setuserInfo] = useState(‘’);
useEffect(() => {
const url = 'https://test.com/v1/getSessionInfoById';
const requestOptions = {
method: 'POST',
headers: { 'Content-type': 'application/json' },
body: JSON.stringify({ sessionId: 'cf209972-51d6-37d5-b9e9' })
};
const fetchData = async () => {
try {
const response = await fetch(url, requestOptions);
const json = await response.json();
console.log("json " + json);
setuserInfo(json);
} catch (error) {
console.log("error", error);
}
};
fetchData();
}, []);
return (
<>userInfo</>
)
};
export default App;
Postman response is
{
"sessionId": "cf209972-51d6-37d5-b9e9",
"userId": "114",
"expirationDate": "2023-04-21",
"keyPropertiesList": [
{
"id": 266277,
"properties": {
"user": {
"firstName": "test",
"lastName": "A",
"fullName": "test A"
},
"userDetail": {
"phoneNo": "666-777-9999",
"email": "[email protected]"
},
"locationID": "78"
}
}
]
}
2
Answers
The api is giving the correct answer however, you are wrongly printing it.
look at this code once, I wrote the right json bt still it says [Object Object] because I’m printing in the console with
+
operator as :console.log("json" + js )
Because you are trying to concatenate a string with an object.
however replacing
+
with,
will give the correct answer.Like this ( because you are not concatenating here, you are just printing those values )
response.json returns the parsed Json as an "Object". You are concatenating this object with a string:
console.log("json " + json);
Hence you will get the String representation. You probably want:
console.log("json ", json);