Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux-Toolkit: how to deal with an entity with compound keys?

I'm trying to use Redux-Toolkit's createEntityAdapter in an entity that has compound keys. For example, my territories entity has a type (municipality, state, biome, etc) and a geocode number. The pair {type, geocode} is the compound key of this entity.

I want to be able to use selectById and other selectors. My first thought was to create an id field that concatenates type, ";" and geocode, but I'm sure there's a better way.

import { createEntityAdapter } from '@reduxjs/toolkit'

const adapter = createEntityAdapter({
    // selectId: (item) => ???,
})

const APIresponse = {
    data: [
        { type: 'state', geocode: 1, value: 123},
        { type: 'state', geocode: 2, value: 66},
        { type: 'municipality', geocode: 1, value: 77},
        { type: 'municipality', geocode: 2, value: 88},
        { type: 'municipality', geocode: 3, value: 99}
    ]
}
like image 267
Rodrigo Amaral Avatar asked Jan 31 '26 05:01

Rodrigo Amaral


1 Answers

I'm a Redux maintainer and the person who implemented createEntityAdapter for RTK.

createEntityAdapter does assume that you have some kind of unique ID field in your data. If you don't have a unique ID field from the original data, you've got three options I can think of:

  • Generate a unique ID for each item when you are processing the API response (but before any "loaded" action is dispatched)
  • Concatenate together some combination of fields to create a synthesized id field when you are processing the API response
  • Implement selectId so that it returns a combination of fields each time
like image 55
markerikson Avatar answered Feb 03 '26 05:02

markerikson