Search code examples
reactjsreduxreact-reduxnormalizrredux-toolkit

Reducer state is not being updated with the new object [redux, redux-toolkit, normalize]


There is a DeliveryManifestView component. It runs an effect which dispatches a thunk.

useEffect - get data

The thunk gets data from the api, then it is normalized with normalizr.

The normalizedData is passed to an action created by redux-toolkit.

get data, normalize, and pass to reducer

And the reducer returns the new object of the entity.

return the entity

It works perfectly on the first run. However if I go to another view then come back

the effect re-runs, the thunk is dispatched,

the data comes from the api,

the data passed to the reducer again and the reducer returns the new data,

but no changes happen in state, I still get the old state.

Here is the action diff from redux devtools

This is on the very first render first run

After going back to another view and coming back

data is not being changed here

No diff in data reducer, even though a new data came from the api.


Solution

  • The problem was that when normalizr gets an empty array it returns an undefined and so reducer returned undefined as well resulting in no changes. Here is the solution I came up with

    enter image description here

    giving a default value to the deliveryPackages.