0

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;
  }
}
hancho
  • 1,345
  • 3
  • 19
  • 39

1 Answers1

1

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

Alex Borodin
  • 1,555
  • 12
  • 26
  • I think that's the worst way to compare two objects. [`_.isEqual`](https://lodash.com/docs/#isEqual) could be a way better choice. – rishat Aug 24 '17 at 20:49
  • Yes, it may be better, if it is not an only place where we need such comparison. Loading the whole library for 1 line of code is not good practice too. – Alex Borodin Aug 24 '17 at 20:53