Ali Shefaee
Ali Shefaee

Reputation: 362

react-redux: make a non-serializable data to serializable to prevent error

I'm using redux-toolkit:

    "react-redux": "^8.0.2",
    "redux": "^4.2.0"

and I want to dispatch an action that passes an html element refrence as payload:

<Stack aria-describedby={id} variant="contained" onClick={(e) => dispatch(open({ele: e.currentTarget}))}
 //...
</Stack>
// slice
const initialState = {
    anchorEl: null,
}

export const loginPopupSlice = createSlice({
    name: 'loginPopup',
    initialState,
    reducers: {
        open: (state,action) => {
            state.anchorEl = action.payload.ele
        },
        close: (state) => {
            state.anchorEl = null
        }
    }
})

but I get error that:

react_devtools_backend.js:4026 A non-serializable value was detected in the state, in the path: `loginPopup.anchorEl`. Value:

How can make payload for dispatch(open({ele: e.currentTarget} serializable?
what i tried:
One way I think to do is to convert HTML Dom to string (because string is serializable) and vice versa. But is it good from performance view?
Notice:
redux dev tools does not work correctly with non-serializable values. So I hope with solving this problem I can make use of it

Upvotes: 0

Views: 1037

Answers (1)

markerikson
markerikson

Reputation: 67489

DO NOT put DOM nodes in the Redux store! Those are A) not "data" or "state", and B) most definitely not serializable:

https://redux.js.org/style-guide/#do-not-put-non-serializable-values-in-state-or-actions

I see your comment about trying to do something with a popup menu. Not sure I have a good answer here, but putting a DOM node in the Redux store is definitely not the right approach.

Upvotes: 5

Related Questions