-1

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": "test@test.com"
                },
                "locationID": "78"
            }
        }
    ]
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
TestUser
  • 247
  • 1
  • 13
  • You've a typo, `console.log("json " + json);` will implicitly call `.toString` on the object and `[object Object]` is the string representation of Javascript objects. You likely meant something more like `console.log("json", json);`. – Drew Reese May 17 '23 at 06:31

2 Answers2

1

The api is giving the correct answer however, you are wrongly printing it.

const js = { name : "sachin" }
console.log("json" + js )

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.

const js = { name : "sachin" }
console.log("json" , js )

Like this ( because you are not concatenating here, you are just printing those values )

sachin
  • 1,075
  • 1
  • 7
  • 11
1

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);

madflow
  • 7,718
  • 3
  • 39
  • 54