0

I am running some trouble with this function when I apply the useEffect hook. Does Anyone know how could I solve this?

const [expenses, setExpenses] = UseState([])

const getItems = async() => {
  try {
    // Right now we are receiving all the expenses and filtering by the username but we should only receive the one from the username --> that will be modified
    const data = await axios.get('https://controladorgastosapi.herokuapp.com/expenses/', {
      headers: {
        username: user.userInfo.username
      }
    })
    const result = data.data
    setExpenses(result)
  } catch (err) {
    console.log(err)
  }
}
useEffect(() => {
  getItems()
}, [expenses])
Michael M.
  • 10,486
  • 9
  • 18
  • 34

1 Answers1

0

You wanted to set value to state when the page loaded. You should remove value inside this quotes "[ ]"

useEffect(() => {
  getItems()
}, [])

Explanation: When the state specified in these quotes changes, useEffect works again. The "expenses" state has a default value of an empty array, useEffect responds to this, calls the "getItems" function, which assigns a value to the "expenses" state, and so on in a circle.

  • Thank you very much! But if I remove the dependency this would only render once, so if I chance sth in the expenses would not render automatically right? My goal is to render the component everytime a expense is deleted – Tomás Gabriel Oct 24 '22 at 23:06
  • @Tomás Gabriel, useEffect in your code is not needed, without a dependency, it will simply receive expenses through axios when the component is first rendered, if something is removed, just execute the getItems () function and everything will be re-rendered automatically. – Oleksandr Guman Oct 26 '22 at 12:57