SecondClassCitizen
SecondClassCitizen

Reputation: 111

Redux connect works but now for all properties from the state

My problem is that props.val works as it should, but props.name does not. Can anyone help me figure out why?

import Device from "../Device/Device";
import { connect } from "react-redux";

const dummy = props => {
  return (
    <div className="container">
      <Device
        name={props.name[0]}
        value={props.val[0]}
      />
      <Device name={props.name[1]} value={props.val[1]} />
      <Device name={props.name[2]} value={props.val[2]} />
    </div>
  );
};

const mapStateToProps = state => {
  return {
    val: state.msgValue,
    name: state.name
  };
};

export default connect(mapStateToProps)(dummy);

In redux devtools, state looks like this:

state = {
  msgValue: [23, 34, 45],
  name: ['item1', 'item2', 'item3']
};

Edit: I have dispatched action on the wrong place and when I dispatched it in the right place, everything was okay.

Upvotes: 0

Views: 44

Answers (1)

Hemadri Dasari
Hemadri Dasari

Reputation: 34014

The only issue I could see in your code is that accessing array with index 3. The state array length is only 3 but you are accessing index 3 element which doesn’t exist

So remove below code from your component

  <Device name={props.name[3]} value={props.val[3]} />

Also do this conditional check

    {Array.isArray(props.name) && Array.isArray(props.val) && props.name.length && props.val.length && (
    <div className="container"> <Device
        name={props.name[0]}
        value={props.val[0]}
      />
      <Device name={props.name[1]} value={props.val[1]} />
      <Device name={props.name[2]} value={props.val[2]} />
      </div>
     )}

Also you make sure you access only available index

Upvotes: 1

Related Questions