gkeenley
gkeenley

Reputation: 7398

How do you render a component based on an AsyncStorage value in React Native?

I have a component that looks like this:

export default class Class1 extends Component {
  render = async () => {
    await AsyncStorage.getItem('someValue', (error, someValue) => {
      return(
        <Class2 prop1={someValue}/>
      )
    }
  }
}

What's happening here is that I need to render Class1 based on the value of someValue that is returned from AsyncStorage. The problem is, you can't make the render() method async because async functions return a promise, and render() needs to return a React component.

Does anyone know how I can do this?

Thanks!

Upvotes: 4

Views: 1567

Answers (2)

Ahmed Sadman Muhib
Ahmed Sadman Muhib

Reputation: 2438

For this kind of tasks, you would put the value in your state. And based on the state, you will render the class as required.

In your componentDidMount of Class1, write:

componentDidMount() {
    AsyncStorage.getItem('value').then((val) => {
        this.setState({ value: val });
    })
}

Then in your Class1 add a method which will generate the class based on state value:

createClass() {
    // do something with the value
    if (this.state.value === somevalue) {
        return (
            <Class2 />
        )
    }
    return null;
}

And in your render method of Class1, type:

render() {
    return (
        { this.createClass() }
    )
}

Upvotes: 1

Vgoose
Vgoose

Reputation: 249

You can set it to state, for example:

componentDidMount() {
  AsyncStorage.getItem('someValue', (e, someValue) => {
    this.setState({someValue})
  }
}

Then you can use someValue from state in your render.

Currently, in addition to the async render issue, since you're already passing in a callback to AsyncStorage.getItem(), I'm not sure what using async/await would do.

Upvotes: 0

Related Questions