Search code examples
reactjsreact-contextreact-state-management

Possible to use React's new Context API programmatically?


I'm trying to have 1 big global state where I can perform actions, but I don't want all those actions to live in the same file.

I want to break actions out to their own files and abstract with a changeState function (like a reducer), but I'm not sure how to do this.

I have an example here. If you click the button, it will show you how far through the app it's gotten: https://codesandbox.io/s/r49qyymjzn

It seems to never hit the {ctx => { console.log('...') }.

Any help would be much appreciated, thank you.


Solution

  • Think of the Context.Provider as a stateful component. The action changeName needs to update the state of the Context.Provider class.

    Changes in context.js

    handleNameChange = changeName;
    
    
    actions: {
      changeName: this.handleNameChange
    }
    

    changeName.js

    export default (e, newName) => {
      e.preventDefault();
      this.setState({ name: newName });
    };
    

    Working sandbox example here