I have the following component:
import React, { useState, useEffect } from "react";
const App = () => {
const [data, setData] = useState<null | any[]>(null);
const [checked, setChecked] = useState(false);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
(async () => {
if (data) {
// Could do something else here if data already exsisted
console.log("Data exists already");
}
const ret = await fetch("https://jsonplaceholder.typicode.com/users?delay=1000", { cache: "no-store" });
const json = await ret.json();
setData(json);
setLoading(false);
})();
}, [checked]);
return (
<>
<h1>useEffect Testing {loading && " ⌛"}</h1>
<hr />
<input type="checkbox" checked={checked} onChange={(e) => setChecked(e.target.checked)} />
<pre style={{ fontSize: "0.8em" }}>{JSON.stringify(data)}</pre>
</>
);
};
export default App;
Currently, my if(data)
is pointless however if I wanted to check the current data
state and then run an asynchronous function based on the state the eslint(react-hooks/exhaustive-deps) tells me the hook is missing the data
dependency, which it is. The problem comes when I add data to the dependency list causing an infinite loop.
Any idea how to resolve this? It feels like it should be fairly simple pattern however everything I find recomends using the extended setState(prev => prev + 1)
overload which doesn't help me in this case.