score:9

Accepted answer

You should check if component is still mounted before update state after an async call

useEffect( ()=> {
       let unmounted = false
       async function getAllPositions(){
            let response = await  axios("http://www.localhost:3000/api/v1/positions");
            if(!unmounted)
                setPositions(response.data)
        }
        let jwt = window.localStorage.getItem('jwt')
        let result = jwtDecode(jwt)
        setUser(result)
        getAllPositions()
        return () => {
             unmounted = true
        }
}, [])

score:8

@Alexander Vidaurre Arroyo's answer is correct. You're essentially need to ensure that state isn't being updated when the component is unmounted.

I tried rewriting his answer a little bit in the spirit of hooks to see how you can extract some of the approach of checking for if a component is mounted to determine if state should be updated.

import React, { useCallback, useRef, useState } from 'react';

const useIsMounted = () => {
  const isMounted = useRef(false);
  useEffect(() => {
    isMounted.current = true;
    return () => isMounted.current = false;
  }, []);
  return useCallback(() => isMounted.current, []);
};

const useAsyncState = (defaultValue) => {
  const isMounted = useIsMounted();
  const [value, setRawValue] = useState(defaultValue);
  const setValue = useCallback((newValue) => {
    if (isMounted()) {
      setRawValue(newValue);
    }
  }, []);
  return [value, setValue];
};

const getAllPositions = async () => {
  const response = await axios("http://www.localhost:3000/api/v1/positions");
  return response.data;
};

function MyComponent() {
  const [user, setUser] = useAsyncState([]);
  const [positions, setPositions] = useAsyncState([]);

  useEffect(async () => {
    const jwt = window.localStorage.getItem('jwt');
    const result = jwtDecode(jwt);
    setUser(result);
    setPositions(await getAllPositions());
  }, [setPositions, setUser]);

  return(
    <div>
      Something
    </div>
  );
}

Related Query

More Query from same tag