nogabemist
nogabemist

Reputation: 487

React Native - Setting state in fetch promise

I have a fetch operation to receive coordinates into map markers. It works but it gives this error

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
at Screens/MapPage.js:71:45 in fetch.then.then$argument_0

The error line is in setLocations(result.data). The application works fine but I realized this error only occurs when I switch screens without waiting fetch completed. If I go back to home page without waiting setLocations is fetched. Is there better way to set the state into fetch result? I don't understand Where I am doing wrong?

        fetch(baseUrl + "api/Product/GetAllProductLocalization", requestOptions)
            .then(response => response.json())
            .then((result) =>  {setLocations(result.data);} )
            .catch(error => console.log('error', error));

Upvotes: 1

Views: 65

Answers (1)

Aleksandar Nikolic
Aleksandar Nikolic

Reputation: 268

You are getting this error most likely because some update before setLocations(result.data) is unmounted the component you called the fetch in.

Meaning, setLocations(result.data) is trying to update the state of a component that has been unmounted at which point it throws a warning.

As a friendly recommendation, you should probably check out react-query library, as well as axios instead of fetch.

You can check the docs on their site

https://react-query.tanstack.com/guides/query-cancellation#using-fetch

Upvotes: 1

Related Questions