Search code examples
javascriptreactjserror-handlingfetch

Trouble with fetch error handling in Reactjs


I'm learning how to use fetch and was trying the following syntax:

const [stuff, setStuff] = useState([]);
const request = "link-to-API";

const data = await fetch(request)
    .then(response => response.json())
    .catch(err => {
      console.log(err);
      return {} //(or [], or an empty return, or any return at all)
    })

setStuff(data.hits)

Then, in the return, I have:

{stuff.map((element) => (
        <Thing
          title={element.label}
          link={element.url}
        />
      ))}

Thinking I could just render an empty object whenever my fetch fails. Except, this works only when the fetch itself works. React gives me the error

"Objects are not valid as a React child (found: TypeError: Failed to fetch)."

But I can't find any solution online. How could I handle the errors just by not rendering anything? (that's not the only part I'm rendering, I just want to render an empty div, not conditionally render that part)


Solution

  • when you use await you can't use then and catch methods

    It's important that you use await in async function

    let data = null
    try{
        const response = await fetch(request)
        data = response.json();
    } catch(err)  {
          console.log(err);
        }