How works useState under the hood if I put it inside for loop. From below code snippet I getting list of only one element.
console.log(names) prints 3 times value of names:
first render -> null
second and last render -> complete array (10 elements)
I know that setNames should be placed outside for loop, but I wonder why it render array 3 times (i expected only 2)
and why I getting ul/li list of only 1 element insted of 10.
const {useState, useEffect} = React;
const url = 'https://api.github.com/users';
const Example = () => {
let [names, setNames] = useState(null)
let list = []
const getNames = async () => {
let response = await fetch(url)
let users = await response.json()
for (let i = 0; i < 10; i++) {
list.push(users[i].login)
setNames(list)
}
}
useEffect(() => {
getNames()
}, [])
console.log(names);
return (
<ul>
{names && names.map((item, index) => {
return (
<li key={index}>{item}</li>
)
})}
</ul>
)
};
ReactDOM.render(
<Example/>,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Try this. Add users first in a list and after the loop, update the state.
const getNames = async() => {
const response = await fetch(url)
const users = await response.json()
let names = []
for (let i = 0; i < 10; i++) {
names.push(users[i].login)
}
setNames(names)
}