Reputation: 417
I'm trying to perform a list query on a dynamo database in my react project but I keep getting the following error
TypeError: patients is undefined
render
C:/Health Project/nutzer-system/src/PatientComponents/listPatients.js:62
59 | console.log(patients)
60 | return (
61 | <div className={classes.root}>
> 62 | <Grid container className={classes.root} spacing={16}>
| ^ 63 | {patients.map( patient => (
64 | <Grid key={patient.id} patient>
65 | <Card className={classes.card}>
here is a look at alittle more of my code
state = {
patients: []
}
componentDidMount = () => {
this.getPatients()
}
getPatients = () => {
API.graphql(graphqlOperation(queries.listPatients))
.then(data => this.setState({patients: data.data.listPatients.patients}))
};
render(){
const { classes } = this.props;
const { patients } = this.state;
console.log(patients)
return (
<div className={classes.root}>
<Grid container className={classes.root} spacing={16}>
{patients.map( patient => (
<Grid key={patient.id} patient>
<Card className={classes.card}>
<CardContent>
<Typography className={classes.title} color="textSecondary" gutterBottom>
{patient.Vorname}
</Typography>
<Typography component="p">
{patient.Nachname}
</Typography>
<Typography component="p">
{patient.Strasse}
</Typography>
If you need to see more code just say and I will add it in. I can't figure out how to resolve this. Any help in solving this will be much appreciated. Thanks!
Upvotes: 0
Views: 314
Reputation: 755
this.state.patients is populated asynchronously, which means you have to make sure it's default value is empty array, that way, render()
won't get the runtime error even if you attempt patients.map. Think of it as [].map
works but undefined.map
doesn't. Try this:
replace
const { patients } = this.state;
with
const { patients = [] } = this.state;
Upvotes: 1