Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of normalizing api responses in a Redux app?

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.

like image 318
U r s u s Avatar asked Feb 02 '16 15:02

U r s u s


People also ask

What is normalized data Redux?

Redux and Normalization Normalization is the concept of flattening data and this comes with great performance increases because data is referenced directly and instantly rather than looped over. This is because normalized nested data is represented by ids which are later used to reference that data.

What is normalized API?

Normalize is a lightweight javascript library with simple and powerful api. Has no dependencies and weighs less than 1KB.

Why is it recommended to normalize the state?

A normalized state is a way to store (organize) data. With this way each entity type will have its own place in the store, so that there is only a single point of truth. This practice is the recommended way to organize data in a Redux application as you can read in the Redux recipes.

What is normalize react?

Normalization is the process of efficiently organizing data.


1 Answers

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; }
}
like image 142
Nathan Hagen Avatar answered Sep 22 '22 18:09

Nathan Hagen