4

I have data that look like this:

{[{id: "1",
stories: [{
    id: "11",
    items: [{ id:"111", title:"bla bla" },{ id:"222", title:"bla bla" },{ id:"333", title:"bla bla" }]
}]

its array of objects that have 3 levels of items.

how do i manage it in the best practice in redux?

Nadav Avisror
  • 153
  • 1
  • 8
  • You might be interested in an answer to a similar question by the author of Redux here: http://stackoverflow.com/questions/33940015/how-to-choose-the-redux-state-shape-for-an-app-with-list-detail-views-and-pagina/33946576#33946576 – Michelle Tilley Jan 25 '16 at 16:08

1 Answers1

4

Check out https://github.com/gaearon/normalizr. It allows you to describe nested data as collections of schemas. For your example, I think you could use:

import { normalize, Schema, arrayOf } from 'normalizr';

const collection = new Schema('collections');
const story = new Schema('stories');
const item = new Schema('items');

collection.define({
   stories: arrayOf(story)
});

story.define({
   items: arrayOf(item)
})

// i'm not sure what your outer result type is, so i've
// just named it 'collection'
const collections = [{id: "1",
    stories: [{
        id: "11",
        items: [{ id:"111", title:"bla bla" },{ id:"222", title:"bla bla" },{ id:"333", title:"bla bla" }]
    }]
}]
const normalized = normalize(collections, arrayOf(collection));
/* normalized === {
  "entities": {
    "collections": {
      "1": {
        "id": "1",
        "stories": [
          "11"
        ]
      }
    },
    "stories": {
      "11": {
        "id": "11",
        "items": [
          "111",
          "222",
          "333"
        ]
      }
    },
    "items": {
      "111": {
        "id": "111",
        "title": "bla bla"
      },
      "222": {
        "id": "222",
        "title": "bla bla"
      },
      "333": {
        "id": "333",
        "title": "bla bla"
      }
    }
  },
  "result": [
    "1"
  ]
} */

The result key tells you that you have received one collection with the id of 1. From there you can index into the entities key, which has been flattened by id. For more on how to then use this in your dispatcher, check https://github.com/gaearon/normalizr#explanation-by-example.

Disclaimer: I have not used normalizr, but since it was written by Dan Abramov (author of Redux) I think you'll be in good hands.

Eric O'Connell
  • 858
  • 5
  • 14