redux-hooks icon indicating copy to clipboard operation
redux-hooks copied to clipboard

feat request: can you export the StoreContext?

Open gcloeval opened this issue 6 years ago • 2 comments

Is it possible to export the StoreContext interface, so that we can access the store via standard useContext, i.e.: const store = useContext(StoreContext);

Similar to how its done here? https://github.com/facebookincubator/redux-react-hook#storecontext

Thanks for the library!

gcloeval avatar Mar 23 '19 23:03 gcloeval

Sure. May I ask what's your use case for it?

esamattis avatar Mar 24 '19 08:03 esamattis

Yeah sure- I have a few legacy client service wrappers that I am converting to be accesible via hooks. Those take in a store as a constructor, then dispatch methods, something like:

export class RdxClient {
  constructor(public store: Store) {
    console.log('new rdx client constructored, store=', store)
  }
 createQuery(requestId: string, query: IQueryRdx) {
 this.store.dispatch(setLeafQuery(requestId, query))
}
}

now I just expose them via hooks:

import { useContext } from 'react'
import { MyStoreContext } from './es-hooks-provider'
import { RdxClient } from '../elastic-ts-dsl-search/rdx-client'
export function useRdxClient(): RdxClient {
  const { store } = useContext<any>(MyStoreContext)
  const rdxClient = new RdxClient(store)
  return rdxClient
}

in this example, i have just added an extra provider with "MyStoreContext" before wrapping yours:

  <MyStoreContext.Provider value={{ store: store }}>
      <HooksProvider store={store}>{props.children}</HooksProvider>
    </MyStoreContext.Provider>

but if you just export your own context I wont need it and can just lift the store from your provider.

gcloeval avatar Mar 24 '19 13:03 gcloeval