Search code examples
reactjsreact-hooksuse-effect

Can't perform react state in React


I'm having a problem. been browsing some questions here but seems doesn't work for me.

I'm getting this error in my three pages when I'm using the useEffect.

Warning: Can't perform a React state update on an unmounted component

This is the code of my useEffect

const UserDetailsPage = () => {


  const classes = useStyles()

  const [userData, setUserData] = useState({
    _id: "",
    name: "",
    phone: "",
    address: "",
    birthdate: "",
    gender: "",
    messenger: "",
    photo: "",
    email: "",
  })
  const [open, setOpen] = useState(false)
  const [loaded, setLoaded] = useState(false)
  const { height, width } = useWindowDimensions()

  const {
    _id,
    name,
    phone,
    address,
    photo,
    gender,
    messenger,
    birthdate,
    email,
  } = userData

  useEffect(() => {
    const user = getUser()

    getUserById("/user/" + user.userId, user.token)
      .then((data) => {
        setUserData(data)
        setLoaded(true)
      })
      .catch((error) => {
        console.log(error)
      })
  }, [])

Solution

  • Short of getUserById returning a cancel token to cancel any inflight network requests, or an "unsubscribe" method, you can use a React ref to track if the component is still mounted or not, and not enqueue the state update if the component has already unmounted.

    const isMountedRef = React.useRef(false);
    
    useEffect(() => {
      isMountedRef.current = true;
      return () => isMountedRef.current = false;
    }, []);
    
    useEffect(() => {
      const user = getUser();
    
      getUserById("/user/" + user.userId, user.token)
        .then((data) => {
          if (isMountedRef.current) {
            setUserData(data);
            setLoaded(true);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    }, []);