How to store the value of useRef() in redux, when it references an audio tag

428 Views Asked by At

I am building an audio app, something like Spotify.

In my App.jsx, I create an audioRef and use it to reference to the html audio element:

const audioRef = useRef()

<audio ref={audioRef} />

I would like to store the audioRef in Redux with redux-toolkit, to make it accessible globally.

I tried doing it like so:

useEffect(() => { dispatch(setAudioRef(audioRef)); }, []);

where setAudioRef is:

setAudioRef(state, action) { state.audioRef = action.payload; },

Unfortunately, I get the following error message:

A non-serializable value was detected in an action, in the path: 'payload'.

The audioRef is used by many different components across the app to check play/pause the audio, access time elapsed, duration, etc.

Any tips would be greatly appreicated!!

1

There are 1 best solutions below

2
markerikson On

Don't. An audio object isn't data or state, and it's not serializable, so it doesn't belong in the Redux store:

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

A better option would be to have a context provider + a useState near the root of the component tree, and put it in there.