Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 213
gkeenley Avatar asked Jul 12 '26 20:07

gkeenley


1 Answers

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() }
    )
}
like image 122
Sadman Muhib Samyo Avatar answered Jul 14 '26 13:07

Sadman Muhib Samyo