Skip to content Skip to sidebar Skip to footer

Normalizr - Is It A Way To Generate Ids For Non-ids Entity Model?

I'm using normalizr util to process API response based on non-ids model. As I know, typically normalizr works with ids model, but maybe there is a some way to generate ids 'on the

Solution 1:

As mentioned in this issue:

Normalizr is never going to be able to generate unique IDs for you. We don't do any memoization or anything internally, as that would be unnecessary for most people.

Your working solution is okay, but will fail if you receive one of these entities again later from another API endpoint.

My recommendation would be to find something that's constant and unique on your entities and use that as something to generate unique IDs from.

And then, as mentioned in the docs, you need to set idAttribute to replace 'id' with another key:

const data = { id_str: '123', url: 'https://twitter.com', user: { id_str: '456', name: 'Jimmy' } };

const user = new schema.Entity('users', {}, { idAttribute: 'id_str' });
const tweet = new schema.Entity('tweets', { user: user }, { 
    idAttribute: 'id_str',
    // Apply everything from entityB over entityA, except for "favorites"mergeStrategy: (entityA, entityB) => ({
      ...entityA,
      ...entityB,
      favorites: entityA.favorites
    }),
    // Remove the URL field from the entityprocessStrategy: (entity) =>omit(entity, 'url')
});

const normalizedData = normalize(data, tweet);

EDIT

You can always provide unique id's using external lib or by hand:

inputData.doctors = inputData.doctors.map((doc, idx) => ({ 
  ...doc, 
  id: `doctor_${idx}`
}))

Solution 2:

Have a processStrategy which is basically a function and in that function assign your id's there, ie. value.id = uuid(). Visit the link below to see an example https://github.com/paularmstrong/normalizr/issues/256

Post a Comment for "Normalizr - Is It A Way To Generate Ids For Non-ids Entity Model?"