Home > Blockchain >  Eslint exhaustive deps warning in useEffect
Eslint exhaustive deps warning in useEffect

Time:02-26

In the useEffect of the component below, I face an ESLint exhaustive-deps warning :

ESlint is telling me that I need to include selectedJar as a dependency, but when I do that the charts load quickly then they all disappear.

I can go on with my development because everything works, but I assume, based on the message from ESlint, that I am doing something wrong.

Can anyone advise me on how this code should actually look?


const Stats: Page = () => {
  const [selectedJar, setSelectedJar] = useState("example"); 
  const [jarData, setJarData] = useState<JarChartData>({} as JarChartData);
  const router = useRouter();
  const jar: string = typeof(router.query.jar) === "string" ? router.query.jar : "";
  
  useEffect(() => {
    const getData = async (): Promise<void> => {
      setSelectedJar(jar);
      const jarData: JarChartData = await getJarData(selectedJar);
      setJarData(jarData);
    }
    getData();
  }, [jar]);
  return (
    <>
      something dope
    </>
  )

CodePudding user response:

You have a potential bug here, in that you both call setSelectedJar and then use selectedJar in the same invocation. This isn't likely to do what you want; selectedJar is not guaranteed to have the updated value until the next render.

Reading your logic, it looks like you want the value you fetch to come from the router all the time, but default to "example" if there is no value in the router; if this is the case, there is no need for the useState. You can just fetch your jar data whenever the value from router changes, defaulting it to "example":

  const router = useRouter();
  const [jarData, setJarData] = useState<JarChartData>({} as JarChartData);
  const jar: string = typeof(router.query.jar) === "string" ? router.query.jar : "example";
  useEffect(() => {
    getJarData(jar).then(data => setJarData(data));
  }, [jar, setJarData]);
  • Related