5

It might be me being thick and very new to Redux, but I would love if somebody could give me a simple use case for using something like normalizr.

I don't understand the example given here How do I handle nested API responses in a Flux application?

I suppose what I'm not getting is why it's hard for Stores to consume nested objects.

My app is a medium-large portal, where users can display lists, create new items and new lists by talking to two different APIs.

Community
  • 1
  • 1
U r s u s
  • 6,680
  • 12
  • 50
  • 88

2 Answers2

6

I normalize all my objects but I don't use normalizr.

I like to normalize because it makes code more readable. An example below. It also makes it much easier to reference objects and eliminate duplication. For example, if you subscribe to a todo item on someone elses list, you either have to return a duplicate version of that todo in the subscriber's subscribedTodos list, or you have to know the user id and todo of the other todo in order to get to it.

Back to readability: Which of these is better to read/understand?

function rootReducer (state, action) {
  const { type, payload } = action;

  if(action.type === MODIFY_TODO) {
    return {
      ...state,
      users: {
        ...state.users,
        [payload.userID]: {
          ...state.users[userID],
          todos: {
            ...state.users[userID].todos,
            [payload.todo.todoID]: {
              ...state[userID].todos[todoID],
              ...todo
            }
          }
        }
      }
    }
  } else { return state; }
}

function rootReducer (state, action) {
  const { type, payload } = action;

  if(type === MODIFY_TODO) {
    return {
      ...state,
      todos: {
        state.todos[payload.todo.id]: {
          ...state.todos[payload.todo.id],
          ...payload.todo
        }
      }
    }
  } else { return state; }
}
Nathan Hagen
  • 12,440
  • 4
  • 26
  • 31
2

Consuming nested object is not necessarily hard.

It all depends on your use case and how your UI is organized.

If it doesn't make sense for you to use normalizr, then don't use it. That module really isn't a requirement.

Simon Boudrias
  • 42,953
  • 16
  • 99
  • 134