Search code examples
reactjsreduxreact-reduxredux-sagareact-context

Access React context value from redux-saga function


I have some variables which are controlled by React Context through React.createContext() with Provider and Consumer component. I'm also using redux-saga, so my question is are there anyway to access this context value in redux-saga function. I'm looking for something like "yield select" statement that works with redux-store.

Anyone who know it please explain to me. Thank you in advances.

P/S: Currently, I pass context value to action object payload when dispatch an action. So in redux-saga, we can use it in action parameter. I don't know whether it's the best practice.


Solution

  • EDIT: There is now a package that allows you to grab context easily, react-outside-call

    You can keep an outside reference of your provider component, and grab the state from that.

    Something like this...

    Provider component

    class AppProvider extends Component {
      state = {
        number: 10,
      }
    
      render() {
        return (
          <AppContext.Provider value={this.state}>
            {this.props.children} 
          </AppContext.Provider>
        )
      }
    }
    

    Apps main entry file, or where ever you reference that provider instance.

    let appProviderRef
    export const getProviderState = () => appProviderRef.state
    
    ReactDOM.render(
      <AppProvider ref={ref => appProviderRef = ref}>
        <App />
      </AppProvider>
    , document.getElementById('root'))
     
    

    You can now grab the state from within your redux sagas (or anywhere you want) synchronously calling getProviderState