Search code examples
jsonreactjsfetchreact-hooks

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

}

Solution

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