Search code examples
reactjsreduxnormalizr

Redux Cannot read Schema Normalizr


i always get error like this:

Uncaught (in promise) TypeError: Cannot read property 'periodListSchema' of undefined

here is my code:

my Schema

import { schema, arrayOf } from 'normalizr';

export const periodSchema = new schema.Entity('activePeriod');
export const periodListSchema = new schema.Array(periodSchema);

My Normalize action

then(response => {
            console.log('normalized response', normalize(response.schema.periodListSchema));

and this is my response

{"activePeriod":[{"periodID":2,"periodName":"Periode 27","startDate":"2016-11-11","endDate":"2016-12-11","remark":"Periode Alpha 27","isActive":"1"}],"status":"OK"}

My Normalzr library is v3.2.2 can someone help me find out what's wrong?, i'm trying to understand this.


Solution

  • 1) Uncaught (in promise) TypeError: Cannot read property 'periodListSchema' of undefined This error has been thrown because response does not have schema property, therefore you can't get periodListSchema property from undefined

    2) To normalize response, you should pass array of periods to normalize func, and specify schema. Also, if you have non-standart name of id property, then you should specify the name in options of schema.Entity constructor, through idAttribute.

    DEMO webpackbin

    Example

    import { schema, normalize } from 'normalizr';
    
    export const periodSchema = new schema.Entity(
      'activePeriods',
      {},
      { idAttribute:'periodID' }
    );
    export const periodListSchema = [periodSchema];
    
    const response = {"activePeriod":[{"periodID":2,"periodName":"Periode 27","startDate":"2016-11-11","endDate":"2016-12-11","remark":"Periode Alpha 27","isActive":"1"}],"status":"OK"};
    
    console.log(
      normalize(response.activePeriod, periodListSchema)
    );
    

    Result

    {
      "entities": {
        "activePeriods": {
          "2": {
            "periodID": 2,
            "periodName": "Periode 27",
            "startDate": "2016-11-11",
            "endDate": "2016-12-11",
            "remark": "Periode Alpha 27",
            "isActive": "1"
          }
        }
      },
      "result": [
        2
      ]
    }