0

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.

mhrabiee
  • 805
  • 10
  • 23
Sagar Pawar
  • 465
  • 4
  • 26
  • You never seem to use that data. Where is jsonobj used? Do you have another .then (which is now receiving a promise of undefined)? – jonrsharpe Dec 28 '19 at 11:51
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe Dec 28 '19 at 11:52
  • @jonrsharpe i am new to react and couldn't understand how to do it. – Sagar Pawar Dec 28 '19 at 12:01
  • How to do *what*? You mention useState, which isn't shown in the question. Give a [mcve]. – jonrsharpe Dec 28 '19 at 12:02
  • @jonrsharpe, edited my question and added code sample that i have tried – Sagar Pawar Dec 28 '19 at 12:06
  • And what's the *problem* with that? You mention an error, but you haven't shown it. One thing that seems suspicious is setting the state prop to an object; maybe the initial value is the same, but *you haven't shown that either*. Re-read [mcve]. – jonrsharpe Dec 28 '19 at 12:09

3 Answers3

1

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!

Adrian Pascu
  • 949
  • 5
  • 20
  • 48
0

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

Amir Rezvani
  • 1,262
  • 11
  • 34
0

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

hotpink
  • 2,882
  • 1
  • 12
  • 15