What is an example of state normalization in a React Redux application?

I read Redux Reducers docs and don’t understand how normalization of the state will work. The current state in this example:

{
  visibilityFilter: 'SHOW_ALL',
  todos: [
    {
      text: 'Consider using Redux',
      completed: true,
    },
    {
      text: 'Keep all state in a single tree',
      completed: false
    }
  ]
}

Can you give an example of how it looks above if we followed below?

For example, saving todosById: {id → todo} and todos: array inside the state would be the best idea in a real application, but the example is simple.

+4
source share
2 answers

This example is straight from Normalizr .

[{
  id: 1,
  title: 'Some Article',
  author: {
    id: 1,
    name: 'Dan'
  }
}, {
  id: 2,
  title: 'Other Article',
  author: {
    id: 1,
    name: 'Dan'
  }
}]

You can normalize this path -

{
  result: [1, 2],
  entities: {
    articles: {
      1: {
        id: 1,
        title: 'Some Article',
        author: 1
      },
      2: {
        id: 2,
        title: 'Other Article',
        author: 1
      }
    },
    users: {
      1: {
        id: 1,
        name: 'Dan'
      }
    }
  }
}

What is the advantage of normalization?

, .

: , . , . : . , .

, . results.

result: [1, 2, 3 ..]

id (. ). entities.

, id 1, - entities.articles["1"].

+3

normalizr .

Normalizr JSON , .

,

[{
  id: 1,
  title: 'Some Article',
  author: {
    id: 1,
    name: 'Dan'
  }
}, {
  id: 2,
  title: 'Other Article',
  author: {
    id: 1,
    name: 'Dan'
  }
}]

{
  result: [1, 2],
  entities: {
    articles: {
      1: {
        id: 1,
        title: 'Some Article',
        author: 1
      },
      2: {
        id: 2,
        title: 'Other Article',
        author: 1
      }
    },
    users: {
      1: {
        id: 1,
        name: 'Dan'
      }
    }
  }
}
0

Source: https://habr.com/ru/post/1651502/


All Articles