useState doesn’t update state in useEffect
i am using useState to update game_cards but when using it in use effect it didn’t worked as expected .
const Cards = ()=>
{
const params = useSearchParams();
var setId = params.get("setId");
const [game_cards,setGameCards] = useState([]);
const [isLoading,setIsLoading] = useState(false);
function loadCards ()
{
setIsLoading(true);
const db = getDatabase();
const query = ref(db,"sets/"+setId);
onValue(query,(snapshot)=>{
setIsLoading(false);
setGameCards(snapshot.val());
alert(game_cards.length);
alert(snapshot.val());
});
}
useEffect(()=>{
loadCards();
},[]);
return(
<DefaultLayout>
<div>
<h3>رقم السيت : {setId}</h3>
{
isLoading ?
"Loading Cards"
:"Cards Loaded"
}
</div>
</DefaultLayout>
);
}
export default Cards;
game_cards.length still = 0
2
Answers
Calling
setGameCards
does not update thegame_cards
immediatly, so trying to get the length of the updated state right after setting it, won’t work.Instead, you can do something like this:
This is an async function so the value will not be available here
alert(game_cards.length);
The "React way" would be to have another useEffect with game_cards as the dependency:
What we are saying is that everytime game_cards changes the alert will be executed.