1
votes

I'm getting the following warning in React

'React Hook useEffect has a missing dependency: 'bakerys'. Either include it or remove the dependency array. You can also replace multiple useState variables with useReducer if 'setFlatbakery' needs the current value of 'bakerys'. (react-hooks/exhaustive-deps)'

bakerys and Flatbakery are react state variables.

export default function App() {
  const [bakerys, setBakerys] = useState([]);
  const [flatbakery, setFlatbakery] = useState({ 
    header: [],
    data: []
  })

  useEffect(() => {
    // fectchData is function to fecth data from API
    fetchData().then((randomData) => {
      setBakerys(randomData);
      setFlatbakery(extractData(bakerys)) // extractData is a function.
    });
  }, []);
return <div className="App"></div>;
}
1
I think that warning is from ESLint, just put to ignore intentionally empty deps: // eslint-disable-next-line react-hooks/exhaustive-deps }, []);MRsa

1 Answers

1
votes

You're setting two state variables at the same time. What is more, one update depends on the other. Don't do that. Simply separate the updates into two separate effects:

export default function App() {
  const [bakerys, setBakerys] = useState([]);
  const [flatbakery, setFlatbakery] = useState({ 
    header: [],
    data: []
  });

  useEffect(() => {
    fetchData().then((randomData) =>
      setBakerys(randomData);
    );
  }, []);

  useEffect(() => {
    setFlatbakery(extractData(bakerys));
  }, [bakerys]);

  return <div className="App"></div>;
}