Reputation: 7348
I have a React Native component that needs to fetch an object from Async Storage in order to render. Something like this.
class Class1 extends Component {
async render() {
let data = AsyncStorage.getItem('data');
return (
<View>
{data}
</View>
)
}
}
The reason I've made me render() method an async function is so that I can await the return of the AsyncStorage.getItem() method, so that the component won't try to return the until after the 'data' object has been returned from Async Storage. However, when I use "async render()" I get "Invariant Violation: Objects are not valid as a React child".
Any tips?
Upvotes: 6
Views: 9944
Reputation:
No need, you want conditional rendering for something like this.
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('data');
if (value !== null) {
// We have data!!
return (
<View>{value}</View>
);
}
} catch (error) {
// Error retrieving data
}
};
Then in your render function, call it.
render() {
return (
{this._retrieveData()}
)
}
Upvotes: 5