dai-shi / react-hooks-global-state

[NOT MAINTAINED] Simple global state for React with Hooks API without Context API

Home Page:https://www.npmjs.com/package/react-hooks-global-state

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Multiple states and reducers

wcisco17 opened this issue · comments

I have 2 files as of right now and both of them have different initialState and reducers, but I've been having some trouble combining them into one

state.ts

const userState: IUState = {
      user: null,
}

const counterState: ICState = {
     counter: number,
}

const state = {
    userState,
    counterState
}

const reducer = combineReducers({
    counter: counterReducer as Reducer<State, ICAction>,
    user: userReducer as Reducer<State, IUAction>,
});

export const { GlobalStateProvider, dispatch, useGlobalState } = createStore(
    reducer,
    state as IState<typeof initialState> | any
);

It's showing up as undefined when I try to run the counter is there anyway to combine them together?

It looks OK at first glance...
Could you create reproduction in codesandbox?

Here I'm running into this error trying to combine multiple state:
Is there any way to do this?

×
Error
Name not Found: 'counter'. It must be provided in initialState as a property key.

https://codesandbox.io/embed/spring-framework-rinu8?fontsize=14

By the way, love the library! You did a really good job on making the whole redux like concept super simple.

The error message means the (combined) state doesn't have counter property.

https://codesandbox.io/s/trusting-ganguly-briq8

Here's the fixed version. Apart from typing, two major notes:

  • when using combineReducers, it needs to specify default state in reducer.
  • useGlobalState has to be used inside of <GlobalStateProvider>

For the latter, I will think about if I can show a better error message.
Thanks for your feedback.

Thank you so much!