coding-healthcare
coding-healthcare

Reputation: 3

Accessing Redux store from Method

I'm currently building a React application which uses the Redux store. I would like to test a particular method called getFacilityName, so I have began refactoring my code.

I need helping accessing the Redux Store inside of my getFacility method.

Method:

import { connect } from 'react-redux';
import { setCMSId } from '../redux/methods.js'

export default (props) => {

  props.dispatch(setCMSId("Hello"));
  console.log("[" + props.getState().cmsNum + "]");

  return "x";

};

I'm calling this method inside of the component CMSForm, which is inside the App.js container. My index.js is where I have created the Redux store.

It looks like I'm not using props correctly. I would like to access & change what's inside the Redux store within my getFacilityName method.

Please let me know if I need to explain more -

Upvotes: 0

Views: 44

Answers (1)

Jeff Astor
Jeff Astor

Reputation: 119

Looks like you haven't connected this component to the redux store. You've imported { connect }, you just need to use it. By wrapping your component with the connect HOC, the dispatch method will be injected into the component. Something like this should work:

import { connect } from 'react-redux';
import { setCMSId } from '../redux/methods.js'

export default connect(state => ({ 
   cmsNum: state.cmsNum  // mapping state to component props
}), {
 setCMSId // automatically dispatched when called thanks to `connect`
})(({ cmsNum, setCMSId, ...props }) => {

  setCMSId("Hello");
  console.log("[" + cmsNum + "]");

  return "x";

});

Upvotes: 1

Related Questions