Search code examples
reactjsreact-hooksstaterender

Why my state doesn't update after get value?


I have a state that should fill with a response of api.

this is my code

  const [name,setName] = useState(null)
useEffect(()=>{
decryption(Cookies.get("__n")).then(res=>setName(utf8.decode(res)));
},[])

but my code doesn't update without refresh page. why this doesn't re-render after set new value in useState?

when i use setName without useEffect its no render happened

this is my decryption function

export const decryption = async (value) => {
  const response = await axios.post(
    "https://00000",
    JSON.stringify({
      value: value,
    }),
    {
      headers: {
        ....
      },
    }
  );
  if(response.data.status==="DONE"){
    return response.data.result.value;
  }else{
    toast.error("خطایی رخ داده است")
  }
};

Solution

  • With useEffect, an empty dependency array means the function inside will only run on mount.

    Adding name to your dependency array so that it will watch and rerun every time name is changed.

      const [name,setName] = useState(null)
    useEffect(()=>{
    decryption(Cookies.get("__n")).then(res=>setName(utf8.decode(res)));
    },[name])
    

    Here is some info on the dependency array in useEffect