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 ?
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 .
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.
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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With