How to separate reducer and Action Type then call it to combineReducers (Ex: 07_middleware)
rimsila opened this issue · comments
I'm new in TS and now I got error type in logger and reducer . Can you have an example about separate reducer thanks you.
========= state.ts =============
import { Dispatch } from 'react';
import { applyMiddleware, combineReducers } from 'redux';
import { createStore } from 'react-hooks-global-state';
import { ActionCounter, initialStateCounter, countReducer } from './counter';
const initialState = {
...initialStateCounter,
};
type State = typeof initialState;
const reducer = combineReducers({
count: countReducer,
});
interface Action {
count: ActionCounter;
}
const logger = ({ getState }: { getState: () => State }) => (next: Dispatch<Action>) => (action: Action) => {
/* eslint-disable no-console */
console.log('will dispatch', action);
const returnValue = next(action);
console.log('state after dispatch', getState());
/* eslint-enable no-console */
return returnValue;
};
export const { dispatch, useGlobalState } = createStore<State, Action>(reducer, initialState, applyMiddleware(logger));
========= conter.ts =============
export const initialStateCounter = {
count: 0,
};
export type ActionCounter = { type: 'increment' } | { type: 'decrement' };
export const countReducer = (state = initialStateCounter.count, action: ActionCounter) => {
switch (action.type) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
default:
return state;
}
};
Did you already solve it?
Did you already solve it?
Yes, I did I just spread the state to one object but I think it not correct one.Do you have some examples about separate multiple state. Thanks you
As far as I understand, separating a state is not an issue in JS. It's only about types in TS, right?
The combineReducers type defined in DT is probably not compatible with react-hooks-global-state or even with React.
If there's no nice solution, I would do something like this:
import { Reducer } from 'react';
const reducer = combineReducers({
count: countReducer,
}) as unknown as Reducer<State, Action>;
If you could make a codesandbox example, I could try fixing with it.