Sagar Pawar
Sagar Pawar

Reputation: 475

Handling Deeply nested Json Objects using useState in Reactjs

Am trying to get value from nested json. but got 'undefined' error. when i display the same object in console, it works fine. I want to fetch particular field from nested json object.

here is the json output from api, i want to fetch userid, name and verified fields from below json

{
status: true,
user:
{
    id: 11362
    phone: "+918971557357"
    name: "Sagar pawar"
    email: null
    bio: null
    address: null
    date_of_birth: null
    token: "EMAWdBl3LDjl1X5veo6VvZBKfgQns5wTFXKWjIh9w4VKKXlclRo5ZBlWaJUBS5ImaVZANN9DlHSbFWquObaW1FIJLVGPqFLWKoPEzKLvZAJakhoTxg5TRTjVtLEVz9R9zAbocwF7dmRdI4GCAMlJdtKOEZAUuOcf6AZD"
    image: ""
    role: "user"
    notification_cleared: {date: "2019-12-28 11:42:34.899503", timezone_type: 3, timezone: "UTC"}
    deleted_by: null
    blocked: 0
    verified: 0
    }
}

and this is the fetch function i tried.

fetch(url, options)
      .then(res => res.json())
      .then(body => console.log("Data Response", body))
      .then(data => {
        const jsonobj = data.user.id;
        console.log("User ID:", jsonobj);
      })

and this one i have tried.

const [responseUserId, setUserId] = useState(userId);
...

fetch(url, options)
    .then(res => res.json())
    .then(res =>
      setUserId({ userId: res.user['id'] })
    )

thanks in advance.

Upvotes: 0

Views: 596

Answers (3)

Adrian Pascu
Adrian Pascu

Reputation: 1039

First and foremost. In your fetch function when you log data, in the second then you don't return any data, so in the third then your callback argument is undefined. After console.log("Data Response", body), you should add return body, so it get's passed down as data in your next then statement.

Second, your id is a string(or number, it doesn't matter). So your responseUserId will be a string. So when setting the state with useState you don't need to pass in an object, just pass the value. Like this : setUserId(res.user['id'])

Hope this helps!

Upvotes: 1

hotpink
hotpink

Reputation: 3226

I will use your last example of a functional component with useState:

You initialize responseUserId with userId. Given the code you provided, that should fail to compile, because userId is not defined. Give it a value, like null, or 0 or an empty string.

If you return an object with only one property, you probably don't need the object data type. In my example data.userId and consequently responseUserId is of type Number.

import React, { useEffect, useState } from 'react';

export default function App() {
  const [responseUserId, setResponseUserId] = useState(null);

  useEffect(() => {
    const url = 'https://jsonplaceholder.typicode.com/todos/1';
    fetch(url)
      .then(res => res.json())
      .then(data => setResponseUserId(data.userId))
      .catch(err => console.error(err));
  }, []);

  return responseUserId && <h3>{responseUserId}</h3>;
}

Upvotes: 0

Amir Rezvani
Amir Rezvani

Reputation: 1504

i create a simple fetch request and setUserId just like you want and it works.

the problem is you use 3 then methods you only need 2. in the third then data is undefind but in second you have what you need.

.then(res => res.json())
.then(body => console.log("Data Response", body))
.then(data => {

https://codesandbox.io/s/reverent-mestorf-o43s1

it is so simple i hope it help you

Upvotes: 0

Related Questions