React Hook useEffect has a Missing dependency: 'storeInfo'

Asked

Viewed 206 times

0

I’m trying to use useEffect for a simple function, but error. It is not updating the page and saving the request I make with the function loadAll in the useState. When I load the page the result of storeInfo is the null which is the default value and not the updated value.

Give the dependency warning ( React Hook useEffect has a Missing dependency: 'storeInfo'. Either include it or remove the dependency array React-Hooks/exhaustive-deps )

  const [storeInfo, setStoreInfo] = useState(null);

  useEffect(()=>{
    const loadAll = async () => {
      let chosenInfo = await Tmdb.getStoreById(635302);
      setStoreInfo(chosenInfo);
    }
    console.log(storeInfo)
    loadAll();
  }, []);

If I put storeInfo in the request dependency array gets infinite loop.

  const [storeInfo, setStoreInfo] = useState(null);

  useEffect(()=>{
    const loadAll = async () => {
      let chosenInfo = await Tmdb.getStoreById(635302);
      setStoreInfo(chosenInfo);
    }
    console.log(storeInfo)
    loadAll();
  }, [storeInfo]);

I don’t know what else to do :( If anyone can help me, I’d be grateful!

1 answer

3


  const [storeInfo, setStoreInfo] = useState(null);

  useEffect(()=>{
    const loadAll = async () => {
      let chosenInfo = await Tmdb.getStoreById(635302);
      setStoreInfo(chosenInfo);
    }
    console.log(storeInfo)
    loadAll();            <=== esta parte modifica o storeInfo
  }, [storeInfo]);        <=== esta parte faz a useEffect rodar quando a referencia do storeInfo muda

Suggestions:

  • In case you don’t need the storeInfo in the useEffect, remove from console.log and of dependency array;

  • In case you need the storeInfo in the useEffect, can access within the setStoreInfo:

    setStoreInfo(currentStoreInfo =>({ ...currentStoreInfo, ...chosenInfo}));

  • In case you need the storeInfo in the useEffect in general, put the storeInfo in a useRef():


const storeInfoRef = useRef()

useEffect(() => { storeInfoRef.current = storeInfo  }, [storeInfo]}

useEffect(()=>{
  const loadAll = async () => {
    let chosenInfo = await Tmdb.getStoreById(635302);
    setStoreInfo(chosenInfo);
  }
  console.log(storeInfoRef.current)
  loadAll();            <=== esta parte modifica o storeInfo
}, [storeInfoRef]);     <=== referencia do storeInfoRef nao vai mudar, so o do storeInfoRef.current, que nao vai rodar o useEffect


Browser other questions tagged

You are not signed in. Login or sign up in order to post.