Redux cannot access action creator before initialization using mapDispatchToProps

Viewed 4301

I've been trying to figure this out for a few hours now and can't make headway.

Question: I'm getting an error "Cannot access before initialization" on this line:

const mapDispatchToProps = { changeGreen };

I'm exporting my action creator from index like this:

export const changeGreen = () => {
  return {
    type: GREEN_ON
  };
};

I'm importing into MyComponent.js like so:

import { changeGreen } from "./index";

I'm mapping to dispatch in the component file like so:

const mapDispatchToProps = { changeGreen };

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(MyComponent);

My App.js looks like:

function App() {
  return (
    <div className='App'>
      <TrafficLight />
    </div>
  );
}

I'm wrapping the App with Provider like so:

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

Any help appreciated.

2 Answers

Figured it out, I wasn't initializing the action creator before the render statement.

Fixed it by adding this before the render statement

changeGreen = () => {
    this.props.changeGreen();
  };

You need to map your action to props and dispatch, it should look like the below

const mapDispatchToProps = (dispatch: any) => {
    return {
        changeGreen : bindActionCreators<any, any>(changeGreen , dispatch)
    }
}

Then you'd call it as such - this.props.changeGreen()

Related