Normalizing simple array with normalizr
Asked Answered
G

1

5

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

Gablet answered 7/3, 2016 at 20:1 Comment(0)
K
7

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'}
    }
  }
}
Kealey answered 7/3, 2016 at 20:41 Comment(1)
Ok my mistake. It turns out that I was tryting to work directly on the array of articles rather than an object with an articles propertyGablet

© 2022 - 2024 — McMap. All rights reserved.