Home > database >  useEffect only updates useState once
useEffect only updates useState once

Time:11-28

useEffect only updates useState once on the first render, but if I refresh the page I got an empty list of data. but when I change something in code.. at first refresh I see the required data of the useState in console, but with every other refresh, I only see an empty array.

    const [transaction, setTransaction] = useState([])
    const [family_group, setFamily_group] = useState([])
    const { id } = useParams();

    useEffect(() => {
        getSingleTransaction()

        }
    , [id])

    const getSingleTransaction = async () => {
        const { data } = await axios.get(`/calc/trans/${id}`)
        setTransaction(data)
        setFamily_group(data['family_group'])
    }
    console.log(transaction, "isssssss")
    console.log(family_group, "igggg")

now I will see the console log data

but once I refresh the page I will get an empty list of data instead.

Thanks for your advice in advance.

CodePudding user response:

console.log is not happening before completing getSingleTransaction due to async nature.

   useEffect(() => {
        getSingleTransaction()
        console.log(transaction)
        console.log(family_group)

        }
    , [])

If you add logs inside getSingleTransaction and if it logs id and data then your code is all good.

    const getSingleTransaction = async () => {

        console.log(id);

        const { data } = await axios.get(`/calc/trans/${id}`)

        console.log(data);

        setTransaction(data)
        setFamily_group(data['family_group'])
    }

Or, Bring the two console logs out of useEffect as it will log whenever the state changes.

As @AndreaCostanzo1 has mentioned in the comment add id as a dependency to the useEffect.

CodePudding user response:

Try this:

const [transaction, setTransaction] = useState([])
const [family_group, setFamily_group] = useState([])
const { id } = useParams();

useEffect(() => {
  const getSingleTransaction = async (objId) => {
      const { data } = await axios.get(`/calc/trans/${objId}`)
      setTransaction(data)
      setFamily_group(data['family_group'])
  }

  if (id) {
    getSingleTransaction(id)
  }
, [id])

console.log(transaction, "isssssss")
console.log(family_group, "igggg")
  • Related