Search code examples
javascriptreactjsreduxreact-reduxredux-thunk

How to reference a react component's state in a redux helper function


I'm new to redux, and I can find lots of info on how to pass a redux state to the component, but not the other way round, so I'm not sure if I'm searching the correct vocabulary. But Essentially I want to be able to reference the current state of a react component in a redux helper function, this is what I've done - and I'm getting TypeError: dispatch is not a function and handleSubmit is just launching as soon as the page is loaded:

App.js

render() {
  return (
    <div className="App">
      <p>{this.state.id}</p>
      <form onSubmit={this.handleSubmit(this.state.id)}>
        <button type="submit">Submit</button>
      </form>
    </div>
  )
}

const mapDispatchToProps = dispath => bindActionCreators({ 
  handleSubmit
}, dispath);

export default connect(
  mapDispatchToProps  
)(App);

reducers.js

export const handleSubmit = (test) => {
  window.open("http://localhost:5000/"+test);
}

//Reducer
export default (state = [], action) => {
  switch (action.type) {
    default:
      return state;
  }
};

Solution

  • First, you don't use the function that react-redux pass through the props and try to call handleSubmit on the component itself.

    You are also calling the function inside onSubmit immediately instead of passing a reference to a function so wrap it in an arrow function and use handleSubmit from this.props

    onSubmit={() => this.props.handleSubmit(this.state.id)}

    Second, the first argument to connect is the mapping function to get a slice of the state called mapStateTpProps by convention, pass in null as the first argument.

    there is also no need to use bindActionCreators and you can just pass an object with functions and react-redux will wrap them in dispatch for you

    export default connect(
      null,
      { handleSubmit }  
    )(App);