简体   繁体   中英

fetching data with react hook returns undefined on nested obj properties

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

}

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

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}

For anyone who is having a similar issue(ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM