I have database with 2 tables Person and City with relationship One-to-Many
Example of row in Person:
{id: 1, name: 'John', city: 5}
Example of row in City:
{id: 5, name: 'New York'}
In React app, I get values from database Postgresql, save it in state and show in component (table):
...
render() {
return (
<table>
<thead>
<TableHeader/>
</thead>
<tbody>
{this.props.person.map(item => {
const city = this.props.city.find(el => el.id === item.city);
return (<TableRow key={item.id} directory={item} directoryC={city}/>);
})}
</tbody>
</table>
);
In TableRow I add it to table rows:
...
render() {
return (
<tr>
<td>{this.props.directory.name}</td>
<td>{this.props.directoryC.name}</td>
</tr>
);
}
This code is works, but in console I see this error:
Uncaught (in promise) TypeError: Cannot read property 'name' of undefined
What happend? How can I fix this error?
Update. Fetch code:
onHandlePersonFetch() {
fetch(`${'127.0.0.1:3000'}/person`, {
method: 'GET'
})
.then((response) => {
if (response.status >= 400) {
throw new Error('Bad response from server');
}
return response.json();
})
.then(data =>
this.setState({ person: data })
);
}
onHandleCityFetch() {
fetch(`${'127.0.0.1:3000'}/city`, {
method: 'GET'
})
.then((response) => {
if (response.status >= 400) {
throw new Error('Bad response from server');
}
return response.json();
})
.then(data =>
this.setState({ city: data })
);
}
fetchmethod which would explain the TypeError of the Promise). Check the console to figure out which file is throwingundefined. That should give you a better idea of where the problem is originating.