2

Im trying to display data that has been fetched. but i cannot seem to display nested objects properties in react. Any ideas? if i log the data i first get a undefined, then the correct data. my guess is that i need to wait for the data to be loaded then display it. but it does work for the title that is not in a nested obj.

function SingleBeneficiary({ match }) {

  const [data, setData] = useState({ data: []});
  const id = match.params.id

  useEffect(() => {
  async function fetchData() {
    const response = await fetch(`http://localhost:8081/v1/beneficiary/${id}`);
    const jsonData = await response.json()
    setData(jsonData)
    }
    fetchData();
  }, [])

  return (
 {data.title} // works
{data.address.careOf} // dont work

The data

{ 
  "title":"myTitle",
  "address":{
    "careOf": "my adress"
  }

}
5
  • It would be better to use useReducer to manage JavaScript objects or arrays as state, + console the json data before setData, Does it give proper output? Commented Oct 4, 2019 at 12:12
  • log the response data, tell us what you get Commented Oct 4, 2019 at 12:15
  • log the response and state data what does it give ? Commented Oct 4, 2019 at 12:16
  • IF i log the jsonData directly after the fetch it returns the correct data 🤨 Commented Oct 4, 2019 at 12:30
  • Before setting state blindly when doing async stuff you should realy check if the component is still mounted the code of useIsMounted is here Commented Oct 4, 2019 at 15:54

4 Answers 4

3

Can you try like this? I set initial data to null, and in return I check if it is not null. If address can be null, additional null check is required.

function SingleBeneficiary({ match }) {

  const [data, setData] = useState(null);
  const id = match.params.id

  useEffect(() => {
  async function fetchData() {
    const response = await fetch(`http://localhost:8081/v1/beneficiary/${id}`);
    const jsonData = await response.json()
    setData(jsonData)
    }
    fetchData();
  }, [])

    return (
      <div>
        {data && (
          <div>
            <p>data.title</p>
            <p>data.address.careOf</p>
          </div>
        )}
      </div>
    );
}
Sign up to request clarification or add additional context in comments.

2 Comments

I dont really understand that syntax? The return ({ dont work
@csk87 this technique is called Inline If with Logical && Operator. You can read more about this in reactjs docs. reactjs.org/docs/…
2

You should check if address has careOf property before using it because first time data will be undefined and in second render it will have the data after the api call.

{data.address && data.address.careOf}

Comments

0

For anyone who is having a similar issue(i.e. fetching data via api and only the first time it runs, it will show the data as undefined but after manual refreshing, it works fine), here is a quick and sketchy addition you might consider alongside with 1. "Inline If with Logical && Operator" method and 2. using useState for checking if the api loading is over. With those three, mine worked.

Try fetching the desired data in the previous page of your app; in this case, add the following lines in any page you'll see before "SingleBeneficiary".

    const response = await fetch(`http://localhost:8081/v1/beneficiary/${id}`);
    const jsonData = await response.json()

Maybe it has to do with npm cache, but not really sure what's going on.

Comments

0

replace

return (
 {data.title}
{data.address.careOf} 
)

with

return (
 {data?.title}
{data?.address?.careOf} 
)

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.