'Entity adapter getSelectors method generates "Cannot read property 'map' of undefined" error
I am trying to use createEntityAdapter
from reduxjs/toolkit
to generate selectors automatically.
I have created a "select all" selector successfully using create selector
:
export const selectEnvironmentsResult = extendedApiSlice.endpoints.getEnvironments.select()
export const selectAllEnvironments = createSelector(
selectEnvironmentsResult,
environmentsResult => environmentsResult?.data ?? []
)
And works fine:
const data = useSelector(selectAllEnvironments) // data is correctly defined :)
But, when I try to use createEntityAdapter
to create the selectors:
export const selectEnvironmentsResult = extendedApiSlice.endpoints.getEnvironments.select()
export const selectAllEnvironments = createSelector(
selectEnvironmentsResult,
environmentsResult => environmentsResult?.data ?? []
)
export const {
selectAll,
selectById,
selectIds,
} = environmentsAdapter.getSelectors((state) => {
const selected = selectAllEnvironments(state) ?? initialState
console.log( selected ) // prints "[]"
return selected
}
)
and use it, I get an error:
const data = useSelector(selectAll) // Uncaught TypeError: Cannot read property 'map' of undefined
Solution 1:[1]
The error was in the transformReponse
value. You should use the adapter.setAll
function:
transformResponse: (responseData) => {
return adapter.setAll(adapter.getInitialState(), responseData)
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rashomon |