Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react native how to get return from a promise

my problem is i want to get a json from this function but all i get is a only a promise and why i choose this way because in app that i'm working on it works dynamicly but the only place that i see i can put this promise is render()

this is my code :

var userInfo = (async()=>{
    var value = await AsyncStorage.getItem("@user_info");
    value = JSON.parse(value);
    return value ;
  })();

and this is my result :

Promise {
 "_40": 0,
 "_55": null,
 "_65": 0,
 "_72": null,
}

but what i want to get is a json what sould i have to do ?

like image 480
shahabvshahabi Avatar asked Nov 13 '17 21:11

shahabvshahabi


People also ask

How do I get my promise results in react native?

To get promise value in React and JavaScript, we can use await . to create the getAnswer function that calls fetch with await to get the response data from the promise returned by fetch . Likewise, we do the same with the json method. And then we call setAns to set the value of ans .

How do I get a returned value from promise?

Promise resolve() method: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.

Does resolving a promise return?

The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

What does a promise then return?

Return value returns a value, the promise returned by then gets resolved with the returned value as its value. doesn't return anything, the promise returned by then gets resolved with an undefined value. throws an error, the promise returned by then gets rejected with the thrown error as its value.


1 Answers

You have to call this function from componentDidMount and after the promise completes, call setState.

Here is a canonical example of how to do this:

class User extends React.Component {
  state = { user: null };

  render() {
     return this.state.user && <div>{this.state.user.name}</div>;
  }

  async componentDidMount() {
    const value = await AsyncStorage.getItem("@user_info");
    if (!this._unmounted) {
      const user = JSON.parse(value);
      this.setState({ user: user });
    }
  }

  componentWillUnmount() {
    this._unmounted = true;
  }
}
like image 96
Brandon Avatar answered Sep 23 '22 18:09

Brandon