Why data is not rendering into template for react and redux?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Why data is not rendering into template for react and redux?



I am new to ReactJS:



My code is :


class HomePage extends React.Component {
render() {
const { users } = this.props;
console.log(this.props.users.items);//Line 1
console.log(this.props.users.items.name);//Line 2

return (
<div className="col-md-6 col-md-offset-3">
<h1>Hi {users.name}!</h1><!--Line 3-->
</div>
);
}
}

function mapStateToProps(state) {
const { users } = state;
return {
users
};
}



For Reducer code:


export function users(state = {}, action) {
switch (action.type) {
case 'SUCCESS':
return {
items: action.users
};
default:
return state
}
}



For LINE 1 its showing data in console but when i try to fetch specific property as in LINE 2 from object it generate an error and also rendering data into template for LINE 3.
For LINE 1 data is :


{id: 3, name: "ahsan", email: "ahsan@gmail.com", age: 55, country: "pdf", …}



enter image description here



For LINE 2 error :


Uncaught TypeError: Cannot read property 'name' of undefined
Consider adding an error boundary to your tree to customize error handling behavior.



I am new to ReactJS, Thanks in advance.





You need to make sure you're grabbing an index in the array this.props.users.items[0].name or key from an object if it's an object this.props.users.items['Some Key'].name
– Fernando Avalos
16 hours ago


this.props.users.items[0].name


this.props.users.items['Some Key'].name





Please add you code as a whole not as separate lines. You are getting users and it contains items which it seems being a single objects. But you are trying to render users.name in your render method.
– devserkan
16 hours ago




users


items


users.name





@FernandoAvalos 'items' is already a key.
– hu7sy
16 hours ago





@devserkan i have update my code and items is key which is return from reducer.
– hu7sy
16 hours ago





Can we see your users shape?
– devserkan
16 hours ago


users




1 Answer
1



I think you can try this


export function users(state = {}, action) {
switch (action.type) {
case 'SUCCESS':
return {
...state
users: action.users
};
default:
return state
}
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

Future solutions