reactjs / reactjs/react.dev

Using fetch in useEffect and checking if the component is mounted before setting state

Đang mở
#2,823 0 bình luận 0 reaction 1 người được giao Xem trên GitHub

@gaearon đang làm issue này rồi.

Từ ngày 11/3/2020.

Ngôn ngữ chính
JavaScript
Star
11.8k
Fork
7.9k
Merge trung bình
1 ngày 11 giờ
Pull request đã merge (30 ngày)
11

Mô tả

Consider the following code:

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

And the effect:

const [result, setResult] = React.useState({
  loading: true,
  data: []
})
const isMounted = useIsMounted();
React.useEffect(() => {
    console.log('in effect')
    fetch('https://jsonplaceholder.typicode.com/todos')
      .then(result => result.json())
      .then(data => {
        //before setting state in async function you should
        //  check if the component is still mounted
        isMounted.current && setResult({ loading: false, data })
      })
  },[isMounted])

This code will start a discussion about this being an anti pattern. I think that it's comparing apples with oranges and that article does not apply here.

The useEffect clean up examples show a situation where variables in the callback's closure don't go out of scope and can cause a memory leak but the fetch example won't have that problem.

Is it possible to provide examples of how to safely combine setting state with asynchronous fetch result while not setting it on unmounted components?

It is possible to cancel a fetch (maybe in all browser with the correct babel configuration) but when using SSR (like next.js) and using something like isomorphic-fetch then this is not an option.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.