Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React fetch api won't return the result

I’m having trouble trying to fetch api from this API https://gutendex.com/books/.

This is my code:

import {useState, useEffect} from 'react'

export default function App() {
  const [data, setData] = useState([])
  const LoadData = async() =>{
    const value = await fetch('https://gutendex.com/books/');
    const res = await value.json()
    setData(res.results[0])

  }

  useEffect(() =>{
    LoadData()
  },[])


  return (
    <div className="App">
       <img src={data.formats.image/jpeg} alt={data.title}/>
    </div>
  );
}

The error it shows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data.formats is undefined

Then i try the return{data.formats} to see what happen.
It shows new error like this

Error Objects are not valid as a React child (found: object with keys
{application/x-mobipocket-ebook, application/epub+zip,
application/rdf+xml, text/html; charset=utf-8, text/plain;
charset=utf-8, image/jpeg, text/html}). If you meant to render a
collection of children, use an array instead.

Can someone tell me what is wrong?

>Solution :

The image is rendered before the API call is complete. When this happens there is no data to display. Change you return statement to this:

 return (
    <div className="App">
       {data && (<img src={data.formats["image/jpeg"]} alt={data.title}/>)}
    </div>
  );

Also, the initial value of data shouldn’t be an array, you should set this to null or undefined.

The image will be hidden until the API call is complete, and data

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading