Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalizing simple array with normalizr

I'm just getting started with using normalizr with Redux and I'm stuck on what seems to me like a simple problem but I could be doing this wrong. So I want to normalize an array like this:

{
  articles: [
    {id: 1, someValue: 'test'},
    {id: 2, someValue: 'test2'}
  ]
}

into a structure like this:

{
  result: {
    articles: [1,2]
  },
  entities: {
    articles: {
      1: {someValue: 'test'},
      2: {someValue: 'test2'}
    }
  }
}

I have tried doing this:

const article = new Schema('articles');
responce = normalize(responce, {
  articles: arrayOf(article)
});

But that gives me a structure that looks like this:

{
  articles: {
    entities: {},
    result: {
      0: {someValue: 'test'},
      1: {someValue: 'test2'}
    }
  }
}

which now has no array of article ids. I am assuming I am missing something here:

article.define({
  ...
});

but can't figure what needs to go there in this simple case

like image 973
jamie holliday Avatar asked Mar 07 '16 20:03

jamie holliday


1 Answers

You don't have to define article. Make sure you've imported everything from normalizr correctly. I tried your code and it gave me the expected result:

import { normalize, Schema } from 'normalizr';

let response = {
  articles: [
    { id: 1, someValue: 'test' },
    { id: 2, someValue: 'test2' }
  ]
};

const article = new Schema('articles');

response = normalize(response, {
  articles: [article]
});

console.log(response);

Output:

{
  result: {
    articles: [1,2]
  },
  entities: {
    articles: {
      1: {someValue: 'test'},
      2: {someValue: 'test2'}
    }
  }
}
like image 76
tobiasandersen Avatar answered Oct 01 '22 04:10

tobiasandersen