Reputation: 2913
I'm trying to get the values from props in my render view.
I fetch a Ecommerce store data from my database.
componentWillMount(){
this.props.dispatch(fetchStore())
}
This actions works and it return the data.
this is my console log
The problem I have is that when I access the props store value. I get this console error
<FormGroup>
<Label htmlFor="name">Name *</Label>
<div className="controls">
<InputGroup>
<Input id="name" size="16" type="text" value={this.props.store.store.name} />
</InputGroup>
</div>
</FormGroup
I figure my view is getting render before my dispatcher finishes getting the request.
I knows this because when I console log the props in my render I get this.
//Inside my render()
console.log(this.props.store)
this outputs.
The first time props store is undefined but once the redux store re-render then I get the Ecommerce store data.
I want to know How can i make my render wait for my data to finish the request before rendering.
this is my actions in case I'm doing something wrong.
I'm using redux-thunk middleware for promises.
import axios from 'axios'
export function fetchStore() {
return function(dispatch) {
axios.get('http://localhost:5000/_Store/Details')
.then((res) => {
dispatch({type: 'FETCH_STORE_FULFILLED', payload: res.data})
})
.catch((err) => {
dispatch({type: 'FETCH_STORE_REJECTED', payload: err})
})
}
}
Upvotes: 0
Views: 1014
Reputation: 3686
You can simply add a check in your render function to check for name prop being present before setting it. This will render blank input initially but will set the name once it is fetched from the API.
<FormGroup>
<Label htmlFor="name">Name *</Label>
<div className="controls">
<InputGroup>
<Input id="name" size="16" type="text" value={(this.props.store != undefined && this.props.store.store != undefined) ? this.props.store.store.name : ''} />
</InputGroup>
</div>
</FormGroup>
Upvotes: 1
Reputation: 281616
You don't wait for the redux store to update before render, rather you put a condition to check for an undefined value like
<FormGroup>
<Label htmlFor="name">Name *</Label>
<div className="controls">
<InputGroup>
<Input id="name" size="16" type="text" value={this.props.store?
this.props.store.store.name: ''} />
</InputGroup>
</div>
</FormGroup>
Upvotes: 1
Reputation: 1515
Try to use componentDidMount
instead of componentWillMount
componentDidMount(){
this.props.dispatch(fetchStore())
}
It's not the best practice to call api in componentWillMount
, as per component life cycle componentWillMount
execute first then render
and then componentDidMount
Upvotes: 0