Home > Software engineering >  why is my state not updated in useEffect?
why is my state not updated in useEffect?

Time:05-04

const user = useSelector(state => state.user)
const [gioHangChiTiet, setGioHangChiTiet] = useState([])
const [gioHangSanPham, setGioHangSanPham] = useState([])

useEffect(() => {
    const dataGioHang = async () => {
        try {
            const res = await axios.get(`${apiUrl}api/giohangs`, {
                headers: {
                    token: `Bearer ${user.user?.accessToken}`
                }
            })
            console.log(res.data.data.sach)
            setGioHangChiTiet(res.data.data)
            console.log(gioHangChiTiet "it is empty")
        } catch (error) {
            console.log(error)
        }
    }
    if (user.user) {
        dataGioHang()
        // console.log(gioHangChiTiet)
    }
}, [user])

That is my code. I trying to save gioHangChiTiet with new data but it's always is empty array. I try console.log this and i think it will work but it's not . But if i change any thing in this code , gioHangChiTiet will update new data and console.log this.Can anyone help me and explain why? Thank you so much . I spent a lot of time figuring out how to solve it :((

CodePudding user response:

const user = useSelector(state => state.user)
const [gioHangChiTiet, setGioHangChiTiet] = useState([])
const [gioHangSanPham, setGioHangSanPham] = useState([])

useEffect(() => {
    const dataGioHang = async () => {
        try {
            const res = await axios.get(`${apiUrl}api/giohangs`, {
                headers: {
                    token: `Bearer ${user.user?.accessToken}`
                }
            })
            console.log(res.data.data.sach)
            // setGioHangChiTiet(res.data.data.sach)
            setGioHangChiTiet(res.data.data)
            console.log(gioHangChiTiet)
        } catch (error) {
            console.log(error)
        }
    }
    if (user.user) {
        dataGioHang()
        // console.log(gioHangChiTiet)
    }
}, [user])

Add user to your dependency array. Otherwise the useEffect wont be able to check your if statement. If you're using CRA you should get a warning in your terminal.

CodePudding user response:

useEffect takes two arguments first one is callback function and second one is dependency array.

useEffect(() => {
// this is callback function
},[ /* this is dependency array */ ])

If you want to trigger the callback function every time a state changes you need to pass that state in dependency array.

useEffect(() => {
console.log(someState)
},[someState])

In above code someState will get logged each time it's value changes.

If your dependency array is empty you useEffect callback function will trigger ONLY ONCE.

In your case if you want trigger callback function on change of user state or any other state simply pass it in dependency array.

CodePudding user response:

Can you give this a try:

const user = useSelector(state => state.user)
const [gioHangChiTiet, setGioHangChiTiet] = useState([])
const [gioHangSanPham, setGioHangSanPham] = useState([])

useEffect(() => {
    const dataGioHang = new Promise((resolve,reject) => {
    ( async() => { 
          try {
            const res = await axios.get(`${apiUrl}api/giohangs`, {
                headers: {
                    token: `Bearer ${user.user?.accessToken}`
                }
            })
            console.log(res.data.data.sach)
            setGioHangChiTiet(res.data.data.sach)
            setGioHangChiTiet(res.data.data)
            console.log(gioHangChiTiet)
            resolve();
        } catch (error) {
            console.log(error)
            reject()
        }})();
})

    if (user.user) {
         dataGioHang().then(()={ console.log(gioHangChiTiet);
     })
     .catch(() => console.log("Error executing dataGioHang"))
   }
}, [user])
  • Related