PubSweet

5. Connect to the store

We've got our action, but we need to dispatch it for the store to respond. We can't import any old dispatch method - we need the dispatch method connected to our specific store.

Import the connect method from the react-redux library into pubsweet-component-hello-world.jsx:

import { connect } from 'react-redux'

In PubSweet, all components are wrapped in a Provider component, which comes from the same react-redux library as connect. PubSweet gives its store to the Provider, whose job is to give all the components inside it access to the store. Thanks to this magic, when we import this connect function, it already knows exactly where our specific PubSweet store lives.

1. connect the component to the store to get the dispatch method

Update pubsweet-component-hello-world.jsx to import and use connect, and add a function called mapDispatchToProps:

import React from 'react'
import { helloClick } from './actions'
import { connect } from 'react-redux'

class Hello extends React.Component{
  render() {
    return (
      <div>
        <button type="button" onClick={helloClick}>click</button>
      </div>
    )
  }
}

function mapDispatchToProps(dispatch) {
  return {
    helloClick: () => dispatch( helloClick() )
  }
}

Hello = connect(
  null,
  mapDispatchToProps
)(Hello)

export default Hello

Here's what's happening:

When we pass mapDispatchToProps into connect, the original component will be able to dispatch( helloClick() ) by calling this.props.helloClick(). Update our button to do so:

<button type="button" onClick={this.props.helloClick}>click</button>

When the button's clicked, helloClick creates an action { type: 'BUTTONCLICK'}, which we then dispatch.

2. Try it out

To test it, run pubsweet start if you're not already running the server. In dev mode, PubSweet logs every action dispatched. When you click the button, you should see our action dispatched.

If connect and mapDispatchToProps are confusing, it's fine. The point of all this is that our component can now use the dispatch method, which is connected to PubSweet's store. If you want to learn more about it, you can read more about props and containers here, and about 'react-redux', the Provider and connect here.

We're dispatching our action, but next we need to tell PubSweet what to do when it sees a 'BUTTONCLICK' action. Let's write a reducer.