Skip to content
Advertisement

How to better setup fetch with useEffect?

Im learning JS and React and I came to the code example below and some parts I don’t understand properly. The second .then is inside useUffect is this ok, or it’s better to be in getData func? Also in render there is data**?**.map and I don’t understand why we need ?, is this ternary operator? Is so I thought that ternary operator requires : as a second parameter. Thanks in advance!

JavaScript

Advertisement

Answer

I think, your code is fine, Move getData and fetchURL into useEffect incase if there’s any error.

Also, You can simply use async/await approach for the same.

JavaScript

? is Called Optional Chain Operator, which will help you to check whether the value is nullish (null or undefined).

Basically, it just doing if (data) { data.map...}

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement