Skip to content

Instantly share code, notes, and snippets.

@joaopslins
Created September 4, 2021 08:55
Show Gist options
  • Save joaopslins/94c597d1a240594a586acb0dd5bb461c to your computer and use it in GitHub Desktop.
Save joaopslins/94c597d1a240594a586acb0dd5bb461c to your computer and use it in GitHub Desktop.
const x = {
entities: {
countries: {
1: { ... }
2: { ... }
},
regions: {
1: { ... },
2: { ... },
}
}
}
// REST response data for GET /country/:id
{
id: 1,
name: 'Japan',
regions: [{
id: 3,
name: 'Kanto',
}, {
id: 4,
name: 'Kansai',
}]
}
// normalizr will output the found entities
// (that you can use to update your store):
data.entities = {
countries: {
1: {
id: 1,
name: 'Japan',
}
},
regions: {
3: {
id: 3,
name: 'Kanto',
},
4: {
id: 4,
name: 'Kansai',
}
}
}
// and the normalized original data (that you can use for UI)
data.result = {
id: 1,
name: 'Japan',
regions: [3,4]
}
// store update could be done like this:
// (this can be done more elegantly)
(store) => {
return {
...store,
entities: {
countries: {
...store.countries,
...data.entities,
},
regions: {
...store.regions,
...data.regions,
}
}
}
}
// So any component that is consuming, let's say, the region with the "Kansai" name, will be updated even though you've fetched from the country endpoint
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment