Search code examples
google-cloud-firestorereduxmiddlewareredux-toolkit

Redux toolkit serializableMiddleware doesn't work


I encountered with an issue of serializableMiddleware in redux toolkit. I need to store firestore timestamps inside my redux store and don't want that serializableMiddleware logged this text:

A non-serializable value was detected in the state, in the path: path to timestamp. Value: nt {seconds: > 1675422816, nanoseconds: 106000000} Take a look at the reducer(s) handling this action.

So i take a look at the serializableMiddleware in redux toolkit docs and find out that there is an option isSerializable?: (value: any) => boolean. When I return true from this method, value should consider serializable, but still logs error out even if I always return true.

I wrote function but it didn't work:

const isSerializable = (value: any) => 
    value instanceof Timestamp || isPlain(value);

const serializableMiddleware = createSerializableStateInvariantMiddleware({
    isSerializable
})

Here is how I setup my store:

export const setupStore = () => {
    return configureStore({ 
        reducer: rootReducer,
        middleware: (getDefaultMiddleware) => 
            getDefaultMiddleware()
            .concat(serializableMiddleware)
    })
}

Solution

  • The problem here is that getDefaultMiddleware() already adds the serializable middleware as part of the default setup. You're creating a second instance of the middleware, but that doesn't change the first instance.

    Instead, you need to customize the first instance by passing the right options to getDefaultMiddleware():

    export const setupStore = () => {
        return configureStore({ 
            reducer: rootReducer,
            middleware: (getDefaultMiddleware) => 
                getDefaultMiddleware({
                 serializableCheck: {
                   isSerializable: myCustomIsSerializableFunction
                 }
                })
        })
    }