0

Problem

I am writing an application in react native but unable to fix this particular warning. I understand this is caused by making a request for data, but the component unmounts before request is completed. Also, i have applied some solutions found here but can't get it to work. This is my code, and i have applied the solution below too.

class PeopleScreen extends React.Component {

      constructor(props) {
        super(props);
        this.state = {
          listData : [ ]
        };
    
      }
  
      componentDidMount() {
        // Get list of people.
        AsyncStorage.getItem("people",
          function(inError, inPeople) {
            if (inPeople === null) {
              inPeople = [ ];
            } else {
              inPeople = JSON.parse(inPeople);
            }
            this.setState({ listData : inPeople });
          }.bind(this)
        );
    
      };
   
      render() { return (
      )

This is the solution i have applied:

 class PeopleScreen extends React.Component {
    _isMounted = false;

      constructor(props) {

        super(props);

        this.state = {
          listData : [ ]
        };

      }

      componentDidMount() {
        this._isMounted = true;

        // Get list of people.
        AsyncStorage.getItem("people",
          function(inError, inPeople) {
            if (inPeople === null) {
              inPeople = [ ];
            } else {
              inPeople = JSON.parse(inPeople);
            }
            this.setState({ listData : inPeople });
          }.bind(this)
        );

      };

      componentWillUnmount() {
        this._isMounted = false;
      }

      render() { return ( 

      )

Also, look at the error: my error here

kpose
  • 23
  • 2
  • 5

2 Answers2

0

You need to wrap your setState with an if statement to check if the _isMounted value is true

if(this._isMounted) {
  this.setState({ listData : inPeople });
}
Jackson
  • 3,476
  • 1
  • 19
  • 29
0

I have a feeling that you could have a problem with asynchronous code in here. Your callback seems fine, and technically should work, but I would suggest you to try rewriting your callback as a Promise resolution.

On top of that you could also improve your code in the following way by getting rid of extra if/else, but that is more of an aesthetic preference.

AsyncStorage.getItem('people').then(async (value) => {
  let inPeople = value ? JSON.parse(value) : [];
  this.setState({ listData : inPeople });
  // or even a one-liner: this.setState({ listData : value ? JSON.parse(value) : [] });
});
Evgenii Klepilin
  • 695
  • 1
  • 8
  • 21