In a component, I am trying to dispatch two different actions from two different reducers. They are updating different states in my application. Here is the partial code for the component:
onSubmit = e => {
e.preventDefault()
const food = {
date: this.state.date,
mealCategory: this.state.mealCategory
}
this.props.addFood(food) //from mapDispatch to props updates the food state, viewing in redux tools shows proper state for food
const meal = this.props.food //comes from mapStateToProps
console.log(meal, 'in form') //logging this shows it's not the updated state I am expecting
this.props.addMeal(meal) //trying to update state from food reducer to the meal reducer, meal reducer is not updated via redux tools
}
.
.
...
const mapDispatchToProps = (dispatch) => ({
addFood: food => dispatch(addFood(food)),
addMeal: meal => dispatch(addMeal(meal))
})
const mapStateToProps = state => ({
food: state.food
})
export default connect(mapStateToProps, mapDispatchToProps)(AddFoodForm)
When I check redux tools my state for food shows correctly. However, adding that state to meal const meal = this.props.food
within my function shows a state that is not updated along with the call to this.props.addFood(food)
which dispatches an action from my food reducer. I am aware the update is asynchronous. How can I update state properly?
Just to clarify, my foodReducer takes care of fetches and through forms adds other properties to the state of foodReducer. Once the submit button is pressed, I have the state with all the properties I need. I want to take that final state and pass it to my mealsReducer. I can't use the food variable because that is just a subset of properties that I want on the state. Not sure, if I properly understood your suggestion.
My foodReducer case:
case 'ADD_FOOD':
{
const { date, mealCategory } = action.payload
const itemDetails = {
date,
mealCategory
}
return { ...state, ...itemDetails }
}
This brings about the final state that I want to add via the mealReducer case:
const mealReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_MEAL': {
console.log(action.payload);
const meal = action.payload
console.log(meal);
return [...state, meal]
}
default:
return state
}
}