Reputation: 1437
I'm running into an issue with my code, I am brand new to React. I am making a simple app where users can log workouts. I have a workout component on my user profile page that I want to render when a user updates his/her workout log. The following code below does the trick, but unfortunately it keeps rendering in an infinite loop. I cannot figure out how to set this conditional so it only renders once with each update.
componentDidUpdate(prevProps, prevState) {
if (prevProps.workouts !== this.props.workouts) {
this.props.requestUser(this.props.match.params.userId);
}
}
Users reducer -
const usersReducer = (state = {}, action) => {
Object.freeze(state)
let newState;
switch(action.type) {
case RECEIVE_ALL_USERS:
newState = merge({}, state, action.users);
return newState;
case RECEIVE_USER:
const member = merge({}, action.user);
member.workouts = Object.keys(action.user.workouts)
newState = merge({}, state, { selected: member } );
return newState;
case RECEIVE_WORKOUT:
const newWorkout = merge({}, state.selected.workouts, action.workout)
newState = merge({}, state, newWorkout);
return newState;
default:
return state;
}
}
Upvotes: 0
Views: 652
Reputation: 2034
Your workouts is an object. You cannot compare two objects because it's two different objects, so these objects are not equal which is true. So, you can use something like this:
componentDidUpdate(prevProps, prevState) {
if (JSON.stringify(prevProps.workouts) !== JSON.stringify(this.props.workouts)) {
this.props.requestUser(this.props.match.params.userId);
}
}
this comparison is rough and depends on an order of keys but should work, also you can use some kind of a deep comparison: Object comparison in JavaScript
Upvotes: 1