KittyCat
KittyCat

Reputation: 527

Map function won't work after react state update

Hi everyone,

I have a map function that maps a data array inside one of my state's. The map function works fine on the first load, but when I start 'pushing' data in the array the following error appears:

TypeError: Cannot read property 'map' of undefined

I don't know what to do next since I absolutely don't know what I'm doing wrong here.

My component:

import React, { Component } from 'react';
import { Button, Table, Input, InputGroup, Container } from 'reactstrap';

import { Person } from './components/Person';
import { getFetch, postFetch } from './utilities/ApiCalls';

export default class App extends Component {
  state = {
    fetchData: null,
    success: undefined,
    name: undefined,
    birthday: undefined
  };

  async componentDidMount() {
    const response = await getFetch('http://127.0.0.1:8000/api/birthday/all');

    this.setState({
      fetchData: response
    });
  }

  addPerson = async () => {
    const { name, birthday, fetchData } = this.state;

    const response = await postFetch('http://127.0.0.1:8000/api/birthday/create', {
      name: name,
      birthday: birthday
    });

    this.setState({
      fetchData: [...fetchData.data, {
        id: response.data.id,
        naam: response.data.naam,
        geboortedatum: response.data.geboortedatum
      }]
    });
  };

  render() {
    const { fetchData } = this.state;

    return (
      <Container>
        <Table>
          <thead>
          <tr>
            <th>Name</th>
            <th>Date</th>
            <th>Age</th>
            <th>Remove</th>
          </tr>
          </thead>
          <tbody>
          {fetchData ? fetchData.data.map((person) => (
              <Person key={person.id} name={person.naam} date={person.geboortedatum}/>
            )) : <Person name="Loading..." date="0"/>
          }
          </tbody>
        </Table>
        <InputGroup>
          <Input type="text" onChange={(e) => this.setState({ name: e.target.value })}/>
          <Input type="date" onChange={(e) => this.setState({ birthday: e.target.value })}/>
        </InputGroup>
        <Button onClick={this.addPerson}>Add Person</Button>
      </Container>
    );
  }
}

Any help is appreciated!

Upvotes: 0

Views: 990

Answers (1)

Daniel Adepoju
Daniel Adepoju

Reputation: 821

Initially, from your render method you hope fetchData is to be an object with data as a key name which would be an array. But your addPerson function changes this.state.fetchData to an array. You can update your setState in addPerson to be

fetchData: { data: [...fetchData.data, { id: res.data.id ... }] }

Upvotes: 1

Related Questions