I have the intention to perform a fetch to my rest api when ever the user updates an input bar. The problem I am having is that the componentDidUpdate method calls the action creator which dispatches the json to the reducer, in turn updating the state and calling componentDidUpdate again. Any ideas or best practices to end the endless cycle? Thanks!
Action Creator:
export const fetchFoods = (dispatch, searchText) => {
return fetch(`/nutrition/${searchText}`)
.then(res => res.json())
.then(json => dispatch({type: 'RECEIVE_FOODS', json}))
}
Reducer:
const foods = (state = [], action) => {
switch (action.type) {
case 'RECEIVE_FOODS':
return action.json
default:
return state
}
}
React Container:
const FoodList = React.createClass({
componentDidUpdate: function() {
fetchFoods(this.props.dispatch, this.props.searchText)
},
componentWillMount: function() {
fetchFoods(this.props.dispatch, this.props.searchText)
},
render: function() {
...
}
})
export default connect(
(state) => {
return {searchText: state.searchText, foods: state.foods}
}
)(FoodList)
mapDispatchToPropswithconnectto trigger an action when the input changes. Also explained here.