Search code examples
reactjsreduxnormalizr

Normalize api response with normalizr


So the endpoint responds with something like this when you request an asset. Bios is just an example.

{
  _embedded: {
    bios: [
      {
        name: 'Blorp Gorp',
        id: 256,
        _links: {},
        arrayCollection: [...],
        objectCollection: [...],
        ...
      },
      ...
    ],
  _links: {},
}

And I'd like to flatten it to something like, and I'm not even sure this makes sense:

{
  results: [256, 257],
  entities: {
    bios: {
      256: {...},
      257: {...}
    },
    arrayCollection: {
      256: [...],
      257: [...]
    },
    objectCollection: {
      256: {...},
      257: {...}
    }
  }
}

But I can't get the Schemas to recognize any nesting before they hit their entity. if I pass normalize(camelizedJson.embedded.bios, bioSchema), it works, but if I pass it normalize(camelizedJson.embedded, bioSchema) I can't get it realize I want to parse the bios.

I suppose I could pass another variable into the middleware that gives it the embedded key to parse successfully.


Solution

  • But I can't get the Schemas to recognize any nesting before they hit their entity. if I pass normalize(camelizedJson.embedded.bios, bioSchema), it works, but if I pass it normalize(camelizedJson.embedded, bioSchema) I can't get it realize I want to parse the bios.

    You probably want normalize(camelizedJson.embedded, { bios: bioSchema }) instead. Schemas can be nested inside plain JavaScript objects, for example:

    normalize(camelizedJson.embedded, {
      bios: bioSchema,
      lols: lolSchema,
      wow: arrayOf({
        wat: {
          ugh: ughSchema
        }
      })
    })