skip to Main Content

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


  1. Calling setGameCards does not update the game_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:

    const value = snapshot.val();
    setGameCards(value );
    alert(value .length);
    
    Login or Signup to reply.
  2. setGameCards(snapshot.val());
    

    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:

     useEffect(()=>{
          alert(game_cards.length);
        },[game_cards]);
    

    What we are saying is that everytime game_cards changes the alert will be executed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search