Search code examples
javascriptreduxnormalizr

Normalizr is not processing data in envelope


I am using normalizr for data that I receive from Api. When I am receiving list I get normalized entities as expected.

But when I send request that updates one entity, I am receiving only one entity wrapped in data envelope witch is not processed by normalizr correctly.

// Normalize setting
import { Schema, arrayOf } from 'normalizr'

export const player = new Schema('players')
export const arrayOfPlayers = arrayOf(player)

//This is what I use for normalize 
response => normalize(response, {players: schema.player})

And I am receiving data like following with only one player in the list:

{
    code: 200,
    message: '',
    data: { 
        players: [{
            id: 20
            username: 'Gamer'
        }]
    }
}

What I should change to retrieve player as normalized entity?

update:

Example of Api call.

  fetch(
    url,
    { credentials: 'include' }
  )
    .then(checkStatus)
    .then(response => response.json())
    .then(response => normalize(response, {players: schema.player})) 
    .then( // dispatch redux action )
    .catch(function (error) {
    })

Solution

  • if you receive array you should use arrayOf ,otherwise refer to object through res.data.players[0]

    change this

    normalize(response, {players: schema.player} ) 
    

    to:

    1)

    normalize(response.data, {players: arrayOf(schema.player) })
    

    result will be

    {
        entities: {
            players: {
                20: {
                    id: 20,
                    username: "Gamer"
                }
            }
        },
        result: {
            players: [
                20
            ]
        }
    }
    

    2)

    normalize(res.data.players[0], player)
    

    result will be

    {
        entities: {
            players: {
                20: {
                    id: 20,
                    username: "Gamer"
                }
            }
        },
        result: 20
    }
    

    webpackbin demo test with other options