Encountering unmounted component error in React Native development

A cautionary error message: unable to update a state in React on an unmounted component.

Although this may seem harmless, it could signify a memory leak in your application. To resolve this issue, be sure to cancel all subscriptions and synchronous tasks within a useEffect cleanup function.

I was utilizing this functionality for navigating to different scenes once the location had been obtained. However, the warning appeared after successfully navigating to the screen.

useEffect ( () => {
        (async () => {
            let {status} = await Location.requestPermissionsAsync();

            if (status !== 'granted'){
                setErrorMsg('Permission to access location has not been granted')
            }
            let location = await Location.getCurrentPositionAsync({});

            const {coords} = location

            if (coords) {

                const {latitude, longitude} = coords;

                let addressResponse: any = await Location.reverseGeocodeAsync({latitude, longitude})

                for (let item of addressResponse){
                    setAddress(item)
                    let currentAddress = `${item.name},${item.street},${item.postalCode},${item.country}`
                    setDisplayAddress (currentAddress)

                    if (currentAddress.length>0){
                        setTimeout(
                            () => {
                                navigate('homeStack')
                            },1000) 
                    }
                    
                      return;
                }
                
            }else {
                
            }
        })();
},)

Answer №1

To ensure safe usage of setState, it is recommended to first check if the component is still mounted. One way to achieve this is by implementing a flag variable named isMounted that can be checked after each asynchronous function call.

function Component() {
 let isMounted = true;
 useEffect(() => {
   (async () => {
        let {status} = await Location.requestPermissionsAsync();

        if(!isMounted) return; // halt execution

        if (status !== 'granted'){
            setErrorMsg('Permission to access location is not granted');
        }
        let location = await Location.getCurrentPositionAsync({});

        if(!isMounted) return; // halt execution
      // ...
   });
 return ()=>(isMounted=false);
}

Alternatively, you can utilize a custom experimental hook that automatically cancels async sequences when the component unmounts:

import React, { useState } from "react";
import { useAsyncEffect } from "use-async-effect2";
import { CPromise } from "c-promise2";

export default function TestComponent(props) {
  // ...
  useAsyncEffect(function* () {
    const { status } = yield Location.requestPermissionsAsync();

    if (status !== "granted") {
      setErrorMsg("Permission to access location is not granted");
    }

    const { coords } = yield Location.getCurrentPositionAsync({});

    if (coords) {
      const { latitude, longitude } = coords;

      let addressResponse = yield Location.reverseGeocodeAsync({
        latitude,
        longitude
      });

      for (let item of addressResponse) {
        setAddress(item);
        let currentAddress = `${item.name},${item.street},${item.postalCode},${item.country}`;
        setDisplayAddress(currentAddress);

        if (currentAddress.length > 0) {
          yield CPromise.delay(1000); // auto-cancellable delay
          navigate("homeStack");
        }

        return;
      }
    }
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a Typescript enum that implements interfaces can be achieved by first defining the enum

Creating a Typescript enum that implements interfaces I currently have these two enums All keys in enum ENNAME should only include keys from enum POSTAG export enum POSTAG { BAD = 0x80000000, D_A = 0x40000000, D_B = 0x20000000, D_C = 0x1 ...

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

The NodeJS namespace does not include the exported member "Global." It is recommended to replace NodeJS.Global with typeof globalThis

Can you show the proper way to utilize typeof globalThis? Please provide a detailed explanation, without taking any shortcuts. interface CustomNodeJsGlobal extends NodeJS.Global { foo: { bar: string | null } } Upon execution, you may encounter the ...

Issue: The code is throwing an error "TypeError: Cannot read property 'push' of undefined" in the JavaScript engine "Hermes

Can anyone assist me with filtering an array of objects in a TypeScript React Native project using state to store array values and filter objects in the array? Having trouble with the following error in the mentioned method: LOG after item LOG inside ...

The type 'Data' is lacking the following attributes from its definition

Being a newcomer to Angular 8, I can't figure out why this error is popping up. If you have any suggestions on how to improve the code below, please feel free to share your tips. The error message reads: Type 'Data' is missing the follo ...

The event listener for 'end' is not executing in a Node.js Firebase and Nylas Express application

I am currently working on setting up webhooks with Nylas. In their provided example, there is a middleware code that I am implementing in my TypeScript project using Firebase as the endpoint. When testing locally with ngrok, the middleware functions prop ...

Problems arise during the installation of TypeScript typings for .NET Core

After downloading VS2015 community edition, I decided to migrate one of my old MVC projects to .NET Core MVC. I used TypeScript for all the client side code in my old project, but now it's becoming a hassle to set up. Despite configuring multiple JSON ...

Discovering various kinds of data with a single generic type

I am looking to define a specific type like this: type RenderItems<T> = { [K in keyof T]: { label: string; options: { defaultValue: T[K]['options'][current_index_of_array]; item: (value: T[K][&apo ...

Unable to send a function as props to a child component in TypeScript

Within my application, I have a parent component that holds a state and a setState function. This state and function are then passed down to a child component in order to retrieve values (such as input field data). When the function is triggered in the chi ...

What is the most efficient way to retrieve a single type from a union that consists of either a single type or an array of types

Is there a way to determine the type of an exported union type by extracting it from an array, as illustrated in the example above? How can this be achieved without directly referencing the non-exported Type itself? interface CurrentType { a: string; b ...

Tips for testing the canActivate guard method in Angular2 using Jasmine

Apologies for bringing up this particular inquiry. It seems that no blog or YouTube tutorials exist regarding testing the canActivate guard file. The official documentation also lacks any information on this topic. Any assistance on this matter would be g ...

What is the best way to showcase a random index of an array in typescript?

Imagine a scenario where you have created a method that captures an array and selects a random position from it. The task at hand is to display one or more of these random positions on the screen. While you have successfully used the *ngFor directive to di ...

What is the best way to have text wrap around an icon in my React application?

I am facing an issue while trying to display the note description over the trash icon in a React app. I have tried various methods but can't seem to achieve the desired effect. Can anyone guide me on how to get this layout? Here is what I intend to a ...

Encountered an error while trying to execute the command "expo install react-native-maps" in a React Native project

Having trouble running the command expo install react-native-maps in my React Native project. Despite trying to delete node_modules and reinstalling them, I keep getting this persistent error. Any help would be greatly appreciated. Thanks in advance! ...

Issue - PerfectScrollbar : Unable to call a function on a type without a defined call signature. The data type 'Number' does not have any suitable call signatures

The following code is running smoothly:- $(".info).scrollTop(0); However, the equivalent code below is encountering an error:- let ele : HTMLElement = document.querySelector('.info'); ele.scrollTop(0); <---- Error Error: - Error - Perf ...

Tips on declaring an object with a nested array of objects in TypeScript

In my code, I have defined two classes. One is called Stuff and the other is called Thing. class Stuff { constructor() { } things: Thing[] = []; name: string; } class Thing { constructor() { } active: boolean; } As I was working on my applicat ...

What is the best way to add all the items from an array to a div element?

I am currently facing an issue where only the last object in my array is being added to my div using the code below. How can I modify it to add all objects from the array to my div? ajaxHelper.processRequest((response: Array<Vehicle.Vehicle>) ...

How can you properly structure chainable functions in Angular?

Recently, I've been working on developing custom functions for my Angular application. Following the official guidelines, I have created an independent library. My goal is to create chainable functions similar to this: var obj = { test : function( ...

In TypeScript, mapStateToProps will throw an error if own props are not returned

Displaying an example linked component below: import React, {FC, ReactElement} from 'react'; import { connect } from 'react-redux'; interface RootState {} interface MyComponentProps { name: string; age: number; } const MyComponen ...

Angular is failing to detect a change in the initial element of an array

In my Angular app, I am working on displaying a list of dates for the current week. Users should be able to view previous weeks by clicking a button, so I am using an Observable to update the array of dates and trying to display the updated array. Althoug ...