Fetching data from an API and putting them inside an array but it works differently in browser/IDE?

It's React. Something weird happens. When I reload directly from the browser, it still logs an empty array, but when I save the file from VSCode, it displays the array just like I wanted.
const [country, setCountry] = useState([]);

useEffect(() => {
axios
.get("https://restcountries.com/v3.1/all")
.then((response) => {
const data = response.data;
const names = data.map((n) => n.name.common);
setCountry(names);
console.log(country);
})
.catch((error) => {
console.log(error);
});
}, []);
const [country, setCountry] = useState([]);

useEffect(() => {
axios
.get("https://restcountries.com/v3.1/all")
.then((response) => {
const data = response.data;
const names = data.map((n) => n.name.common);
setCountry(names);
console.log(country);
})
.catch((error) => {
console.log(error);
});
}, []);
2 Replies
Tenkes
Tenkes2y ago
try putting api url in separate variable, and then use it as dependency in useEffect
meku
mekuOP2y ago
Hi guys I'm back with the explanation as why this is happening. It's not that states don't update "immediately" it's that there's a big confusion about what a re-render or state update is. React is not doing what you think it's doing Take a look at a very basic state example like this:
const [num, setNum] = useState(0)
const [num, setNum] = useState(0)
the num variable is a constant number which cannot be reassigned, similar to if it was declared like this:
const num = 0
const num = 0
there's nothing any framework or anything in the language could do to update that num from a 0 to a 1. It's a constant number and can never change, this is true for all state variables. So how does that number change when you call setNum? Well, it doesn't. Calling that setter tells React to run your function again, but this time it will give your function a value of 1 instead of 0. The state doesn't get mutated. You schedule your component to be called/rendered again. But not only that. There's no way something like this could EVER work
const [num, setNum] = useState(0)

console.log(num) // 0
setNum(1)
console.log(num) // 1 MAGICALLY? not possible
const [num, setNum] = useState(0)

console.log(num) // 0
setNum(1)
console.log(num) // 1 MAGICALLY? not possible
There's nothing javascript could do to make that second console.log return anything other than 0 if num is just a normal number. I think understanding that helps realize why and how react works the way it does. now, to this actual behaviour, the HMR (hot module reload) from saving is able to run the component again without unmounting it while, in the browser, you get a full reload of the page, completely remounting the component
Want results from more Discord servers?
Add your server