Skip to content

Instantly share code, notes, and snippets.

@hbarcelos
Last active June 11, 2020 19:43
Show Gist options
  • Save hbarcelos/8c62474897bc564b6073cb59a429124a to your computer and use it in GitHub Desktop.
Save hbarcelos/8c62474897bc564b6073cb59a429124a to your computer and use it in GitHub Desktop.
RTK vs Nested Immer's Produce

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;
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment