Jinto Antony
Jinto Antony

Reputation: 468

setState not working inside AsyncStorage in react native?

setState not working inside AsyncStorage in React Native.

constructor(props) {
    super(props);
    this.state = {userId: ''};
}

componentDidMount() {

    AsyncStorage.getItem('USER_ID', (err, result) => {
        if (!err && result != null) {
            this.setState({
                userId: result
            });
        }
        else {
            this.setState({
                userId: null
            });
        }
    });

    alert(this.state.userId);
    let userId = this.state.userId;

    fetch('http://localhost/JsonApi/myprofile.php', {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            userId: userId,
        }),
    })
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({userDetails: responseJson});
        })
        .catch((error) => {
            console.error(error);
        });

}

Setting the userId value using setState and alert returns no value at all. Tried other solutions from Stackoverflow but not as per my expectation.

Note: Code updated. After getting userId from AsyncStorage, it will be passed to fetch. Here, userId value is missing.

Upvotes: 0

Views: 1776

Answers (3)

anil sidhu
anil sidhu

Reputation: 963

2 ways to do this. One is Simple but other is correct way according to react recommendation

One is here- pass value to state directly.

 .then((responseJson) => {
           // this.setState({userDetails: responseJson});
      this.state.userDetails=responseJson;
     this.setState({});   //for update render
        })

Second Way is here

in the render function Check state Value like this .if UserDetails state is null it will be not give you error whenever userDetails state get data render execute again and provide perfect result.

          render() {
    return (
      <div>
        {this.state.userDetails ?
          this.state.userDetails.map((data, index) =>
            <tr key={index}>
              <td>{data.userName}</td>
              <td>{data.userEmail}</td>
            </tr>
          )
          : null
        }
 </div>)}

Let me know gain. if facing issue

Upvotes: 2

Khemraj Sharma
Khemraj Sharma

Reputation: 58934

I don't know why you wrote so much code.

First way

AsyncStorage.getItem("USER_ID").then((value) => {
       console.log("userId in async = " + value);
       this.setState({
            userId: value
     });
});
  • You don't need to check error & result both because if that is null, you are setting userId null in state. so you can directly set value to state userId.
  • Also set a log to see what is output of your async storage userId.
  • Please also verify that you are setting value in "USER_ID" somewhere.

Second way

There can different ways also like using async method.

const getUserId = async () => {
  try {
    const userId = await AsyncStorage.getItem('USER_ID') || 'none';
  } catch (error) {
    // Error retrieving data
    console.log(error.message);
  }
  return userId;
}

and you can use

this.setState ({
  userId : getUserId()
});

I don't like this way because I need to create another method with async & await keywords.

I use the first way so.

Update

Do your work related to userId inside getIten();, because you alert userId immediately after calling AsyncStorage. And AsyncStorage returns value after you call alert.

AsyncStorage.getItem("USER_ID").then((value) => {
       console.log("userId in async = " + value);
       this.setState({
            userId: value
     });
       alert(this.state.userId); // move this line here
});

// removed from here

Upvotes: 0

ChintaN -Maddy- Ramani
ChintaN -Maddy- Ramani

Reputation: 5164

Try to alert after updating state. You will get callback once state is updated.

this.setState({
                userId: result
            },function(){
        console.log("userId in async = ", this.state.userId);
        alert(this.state.userId);
});

Upvotes: 0

Related Questions