AlxVallejo AlxVallejo - 1 year ago 40
React JSX Question

React Native: make API request, set State, and THEN render?

Sorry if this is obvious somewhere in the documentation, but I am trying to wait until my state is set on a parent component before rendering a child component:

Paraphrasing:

class Parent extends Component {

componentWillMount() {
firestack.database.ref()
.then((snapshot) => {
this.setState({myVal: snapshot.val})
})
}

render() {
// Renders before request finishes setting state,
// Child component receives an undefined val
return (
<ChildComponent
myVal={this.state.myVal}
/>
)
}
}


My render hits before the request finishes, so I'm not able to pass the new State to the child component's constructor. How can I properly do this?
Hopefully this is low hanging fruit to someone.

Answer Source

First, I recommend moving your async request to componentDidMount. Not mandatory, but it's a better point in the life-cycle. Your component will need to able to handle myVal == undefined anyway.

Then, don't render the child component until myVal is available:

render() {
  return (
    <div>
      { this.state.myVal && <ChildComponent myVal={this.state.myVal} /> }
    </div>
  )
}

Or perhaps, render a spinner instead:

render() {
  return (
    <div>
      { this.state.myVal 
        ? <ChildComponent myVal={this.state.myVal} />
        : <Spinner />
      }
    </div>
  )
}

Note:

  • You can't use if inside JSX, so this not-so-kosher use of && is required to keep the syntax compact. A common pattern.

  • You can have a this.state.isReady boolean instead of asking for the presence of a specific value. Another common pattern.

  • If ChildComponent is the only element you're going to render, you may not need the <div /> wrapper, but you usually do for some reason or other.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download