Bernardo Benini Fantin
Bernardo Benini Fantin

Reputation: 103

How to clean up React-Native useEffect with axios

Currently I have defined in a functional component a useEffect as below

useEffect(() => {
 (async function () {
   posts.current = await BlogConsumer.getBlogPosts();
   setLoading(false);
 })();

 return () => {
   BlogConsumer.call_controller.abort();
 };
}, []);

where this BlogConsumer is defined as below

class BlogConsumer {
  static posts = {};
  static call_controller = new AbortController();

  static async getBlogPosts() {
    await axios
      .get('https://nice.api', {
        signal: this.call_controller.signal,
      })
      .then(response => {
        // treatment for success
      })
      .catch(error => {
        // treatment for erros
      });

    return this.posts;
  }
}

export default BlogConsumer;

The overral ideia is that in the render of the component I'll be calling a static method from my consumer and will retrieve the necessary data. For the pourpuse of not having memory leaks, I have my callback function in my useEffect that will abort my call whenever I unmount the component, but this is not working. React's message of Warning: Can't perform a React state update on an unmounted component. still appears if I enter the component and leave the screen before the API call is finished. I don't know where I am wrong, so I'd like a little help.

Thanks in advance.

Upvotes: 1

Views: 403

Answers (1)

Amit Dutta
Amit Dutta

Reputation: 201

You could just cancel the request on unmount. Like this:

export const fetchData = async (signal) => {
  try {
    const res = await instance.get("/pages/home", {
      signal,
    });
    return res.data;
  } catch (error) {
    return Promise.reject(error);
  }
};

useEffect(() => {
  const controller = new AbortController();
  fetchData(controller.signal);
  return () => {
    controller.abort()
  };
}, []);

Upvotes: 1

Related Questions