This code doesn't quite work. There is an issue with the Immer proxy being revoked.
I didn't have the time to dig into this, so the solution was to not use produce in createStateMachineReducer.
| export default function createStateMachineReducer( | |
| stateMachine, | |
| createContextReducer | |
| ) { | |
| const contextReducer = createContextReducer(stateMachine.context); | |
| return produce( | |
| ( | |
| stateWrapper = { | |
| state: stateMachine.initial, | |
| context: stateMachine.context, | |
| }, | |
| action | |
| ) => { | |
| const target = stateMachine.states[stateWrapper.state]?.on?.[action.type]; | |
| if (target) { | |
| stateWrapper.state = target; | |
| stateWrapper.context = contextReducer(stateWrapper.context, action); | |
| } | |
| } | |
| ); | |
| } | |
| function createContextReducer(initialState = {}) { | |
| return createReducer(initialState, { | |
| [activate.start]: (state, action) => { | |
| state.activatingConnector = action.payload.name; | |
| }, | |
| [activate.success]: (state, action) => { | |
| state.activatingConnector = null; | |
| state.currentConnector = action.payload.name; | |
| state.error = null; | |
| }, | |
| [activate.error]: (state, action) => { | |
| state.currentConnector = null; | |
| state.activatingConnector = null; | |
| state.error = action.payload.error; | |
| }, | |
| [deactivate]: () => initialState, | |
| [changeAccount]: (state, action) => { | |
| state.account = action.payload?.account ?? initialState.account; | |
| }, | |
| [changeChainId]: (state, action) => { | |
| state.chainId = action.payload?.chainId ?? initialState.chainId; | |
| }, | |
| [setError]: (state, action) => { | |
| state.error = action.payload?.error ?? initialState.error; | |
| }, | |
| }); | |
| } |