0

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

Ali Shefaee
  • 327
  • 3
  • 12
  • what are you trying to achieve by adding an html-element to the store? Do you want to add that element later in another place? – Dmitriy Zhiganov Jun 19 '22 at 10:26
  • please take a look at [popover ui form mui.com](https://mui.com/material-ui/react-popover/#anchor-playground). it's used to define where to open that popover window. however I can use local states and not using redux for that, but first I wonder if there is a solution to solve this. – Ali Shefaee Jun 19 '22 at 10:31
  • Maybe you should only store the window state (opened/closed) and position, not the whole element? – Dmitriy Zhiganov Jun 19 '22 at 10:44
  • @DmitriyZhiganov I edited question (add ```createSlice``` code) for clarification. I know what you mean and maybe I do that, thanks – Ali Shefaee Jun 19 '22 at 11:05

1 Answers1

3

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.

markerikson
  • 63,178
  • 10
  • 141
  • 157