Reputation: 585
I have a react app that has two components one Customer and another called Tags. The Customer sends its state's tags value to Tags. As following:
Customer.jsx
import React from "react";
import Tags from "./Tags.jsx";
export default class Customer extends React.Component {
constructor(props) {
super(props);
this.state = {customer:''};
}
componentDidMount(){
const url = `http://localhost:3000/api/customers/${this.props.params.id}`
fetch(url)
.then(res=>res.json())
.then(data=>{
console.log(data);
this.setState({
customer: data
});
})
.catch(error=>{
console.log(error)
});
}
render() {
return (
<div>
Company Name :{this.state.customer.companyName}
Customer Name :{this.state.customer.name}
Tags: <Tags tags={this.state.customer.tags} />
</div>
);
}
}
Tags.jsx
import React from "react";
export default class Tags extends React.Component {
constructor(props) {
super(props);
}
render() {
let tags = this.props.tags.map(tag=>{
return (<span>tag</span>);
});
return (
<div>
{tags}
</div>
);
}
}
When I run the code I get, "TypeError: Cannot read property 'map' of undefined(…)". If I replace below from Tags.jsx
let tags = this.props.tags.map(tag=>{
return (<span>tag</span>);
});
with
console.log(this.props.tags);
The output is an array. What is happening? I really do not understand. What can I do?
Upvotes: 1
Views: 1655
Reputation: 15550
In the constructor of Customer
you are defining the state of a customer
as a string, not an object. You should change it to reflect the actual customer properties, ie:
this.state = {customer: {name: '', tags: []}};
Upvotes: 1
Reputation: 18684
It's undefined, because of you're making an API call and the data isn't returned yet.
In your Customer
component you can check the existance of this.state.customer.tags
and if exist - then render the tags.
Somethling like that:
{ this.state.customer.tags ? <Tags tags={this.state.customer.tags} /> : null }
Upvotes: 1