user15570208
user15570208

Reputation:

How can I use the init function only the first time?

How can I use this fetchItems function only the first time?

every time this setBrands function is used, it activates this fetchItems function and sets the starting values, I want it to be invoked only once

const [brands, setBrands] = useState({})

//brands is like this brands={CAT: "", RET: "", RTF: "", NW: ""}

useEffect(() => {
    const fetchItems = async () => {
      for (const b in brands) {
          brands[b] = await getCarts(b.id) //i am using like this brands[b] = await getCarts(b.id), but i think that is bad, i have to use setBrands()?
      }
    }
    fetchStoreItems()
  }, [brands])

return (
    <>
          <CartForm
            setBrands={setBrands}
          />

i am updating from CartForm the brands with this function setBrands

note: if i delete the brand dependencies i get this error warning React Hook useEffect has a missing dependency: 'brands'. Either include it or remove the dependency array react-hooks/exhaustive-deps

Upvotes: 0

Views: 76

Answers (1)

koralarts
koralarts

Reputation: 2112

useEffect's dependency array affects when the callback gets called. If you want something to happen only during the mount, you need to have an empty dependency array.

useEffect(() => {
  // do your fetch here
}, [])

Sidenote:

useEffect(() => {
  // Gets called on first render
}, [])

useEffct(() => {
 // Gets called when value changes
}, [value])

useEffect(() => {
  // Gets called every render
})

Update:

const [brands, setBrands] = useState({})

useEffect(() => {
  ...
  for () {
    const data = await getCart(id)
    setBrands((prevBrands) => ({
      ...prevBrands,
      [key]: data
    }))
  }
  ...
}, [setBrands])

Upvotes: 2

Related Questions