I updated my packages and VScode told me that createStore was depreciated. So I went about replacing it
My store file, I have included the original line as a comment at the bottom
import { configureStore } from '@reduxjs/toolkit'; import { Action, createStore } from 'redux' export type State = { context: AudioContext | null} export const START_AUDIO = "startAudio"; const initialState = {context: null} const reducer = (state: State = initialState, action: Action<String>) => { switch (action.type) { case START_AUDIO: if (state.context == null) { return { ...state, context: new AudioContext() } } } return state } export const Store = configureStore({reducer}) // export const Store = createStore(reducer)
Using redux
export function AudioContext() { const dispatch = useDispatch<Dispatch<Action<String>>>(); const context = useSelector((state: State) => state.context) return ( <button disabled={(context == null) ? false : true} onClick={() => dispatch({type: START_AUDIO}) }>Start Audio Context</button> ) }
App component
import '../styles/globals.css' import Head from 'next/head' import { Store } from '../code/util/store/store' import { Provider } from 'react-redux' import { AppProps } from 'next/app'; export default function MyApp({ Component, pageProps }: AppProps) { return (<> <Head> <title>Test App</title> <link rel="icon" href="/favicon.ico" /> </Head> <Provider store={Store}> <Component {...pageProps} /> </Provider> </>) }
With configureStore()
the console is giving me a warning about putting non-serizible objects in state. They say its possible but when I try to use it i get a Maximum call stack size
error.
I have tried removing other uses (apart from setting it) of the redux state object and I still got both errors, I have also tried using a string, this removes the warning and the error. So it would seem that using an AudioContext
in state isn’t supported any longer for whatever reason.
Am I doing this wrong? Should I stop using Redux for this? How else can I achieve this?
I found this issue on github however, according to my node_modules
im running 7.18.0
of @babel/core
Advertisement
Answer
Generally, Redux is a state management tool – state meaning pretty much: data. Usually that data should be represented as a plain JavaScript object or array, not a class instance.
What you are doing here is more of a “dependency injection” use case: you have a certain class with provided functionality that you want to pass down to child components.
In this case I’d recommend you to use React Context, as Context is a dependency injection mechanism (but not very suited for state value propagation – but that’s nothing you want to do here in the first place).