0

I'm kind a new to using userReducer with Context API, so I'm not sure how I can call dispatch function from another useReducer.

useReducerB

...code...
function someFunction()
{
    dispatch(otherActions.B) // this action i like to call from another reducer
}

useReducerA

const { someFunction } = useContext();

dispatch(actions.A); // this is the current reducer
someFunction(params) // dispatch action from another reducer

App

<ContextB.Provider value={someFunction}>
   <ContextA.Provider value={...}>

As u can see the provider for the function is level above the context where I like to call dispatch.

I found out that u can write custom combine reducers utils, but I like to know if this is possible.

I'm getting error XXX is not a function...

Br, Igor

  • You'll need to import it into the ContextA Provider. The same way you'd import it into a component. This means you'll need to export dispatch or another function that calls dispatch. – Mark Swardstrom Nov 16 '20 at 21:39
  • That what i'm doing with ContextB in the example... i'm exporting all the state and dispatch functions... so I'm expecting that with useContext(ContextB), I can call the function as it this... but I'm getting it's not a function... – Игор Ташевски Nov 16 '20 at 21:41
  • I think there are better ways you can do than calling other `dispatch` from another `reducer`. Since every `reducer` gonna holds their **own** `state` and `function` or `action` of their own. Then calling the `action` should be done in the component. I don't know whether [this](https://stackblitz.com/edit/react-gkhyw2?file=src%2FApp.js) or not. Just have a look and try to work around it. – lala Nov 16 '20 at 23:09
  • I know that there is better options, at least i can wrap everything with combine reducers... the problem is, i like to decouple some data, now i store in user object after login and I don't like that... they belong to another reducer... so far useContext returns undefined, but if i call useXXX() than i store data in 'that' state reducer, but after that the component does not retreive the same reference, and using useContext(ContextX), returns empty data... so i'm confused how to achieve this.. .even I'm aware of tight coupling... – Игор Ташевски Nov 16 '20 at 23:22
  • @lala even this example is good and clean... i'm not sure if solves that I like to extract data and function from another context, into reducer that is connected with it's own context... the provider send data to child elements... i need to provide those in another hook, which is not child... – Игор Ташевски Nov 16 '20 at 23:31

0 Answers0