15

I have the following URL: http://localhost:4400/skills/3

In my react component I then have:

  constructor(props) {
    super(props);
    this.state = { skill_id: props.match.params.skill_id };
  }

....

const mapStateToProps = (state, ownProps) => {
  return {
    skill_id: state.skill_id,
    ratingsBySkillId: state.rating.by_skill_id.find(el => el.skill_id === skill_id)
  };
};

The problem is state.skill_id is not available in mapStateToProps? Why? How can I use params in mapStateToProps?

halfer
  • 19,824
  • 17
  • 99
  • 186
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012
  • 1
    Check this answer as well https://stackoverflow.com/questions/44673079/cannot-read-property-query-of-null-in-react-js/44674408#44674408 – Shubham Khatri Jun 23 '17 at 16:27
  • 1
    @ShubhamKhatri has answered it very well in the above link. Refer to that, that's the right solution – VivekN Jun 23 '17 at 17:09

3 Answers3

15

This ended up working:

const mapStateToProps = (state, ownProps) => {
  const skill_id = ownProps.match.params.skill_id;
....
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012
2

so what you would want to do is map skill_id in mapStateToProps to the value that is stored in the state from react-router. Then you would just bring in skill_id

Also I would recommend some logic just to check if skill_id is undefined as that key only is generated in the object if the user has a value for the skill_id

 constructor(props) {
  super(props);
  this.state = { skill_id: props.skill_id };
}

....

const mapStateToProps = (state, ownProps) => {
  return {
     skill_id: (('skill_id' in state.routing.locationBeforeTransitions.query) ? state.routing.locationBeforeTransitions.query.skill_id: false),
     ratingsBySkillId: state.rating.by_skill_id.find(el => el.skill_id === skill_id)
  };
};

Hopefully that helps but your value should be in the routing object of the state

Ali
  • 633
  • 1
  • 9
  • 20
1

If your using react router, just use this.props.params.id.

this depends on how you defined the router though. if your router is like

<route path = `/skills/:id` component = {yourComponent} />

then it works. but if your router is like

<route path = `/skills/:number` component = {yourComponent} />

then you have to do this.props.params.number

vineeth
  • 114
  • 1
  • 14
  • `this` is not defined in `const mapStateToProps = (state, ownProps) => {` – AnApprentice Jun 23 '17 at 21:24
  • I Must have mis understood your question, Do you want the id from the URL? http://localhost:4400/skills/3 in this case 3? or are you storing the id in the redux store? – vineeth Jun 25 '17 at 20:49