2

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)

2 Answers 2

3

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);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

since, its a functional component, you cannot have a random retrun statement returning nothing. the return will result in "Error: App(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."
0

you can try removing the await keyword, as you are using .then also the datafetching part should be included inside useEffect

const [stuff, setStuff] = useState([]);
const request = "link-to-API";
    
useEffect( ()=> {
    fetch(request)
    .then(response => response.json())
    .then(data => setStuff(data.hits))
    .catch(err => {console.log(err)})
},[])

1 Comment

Not returning anything gives the same problem, I'll edit the question

Your Answer

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