Search code examples
reactjsaxiostypeerrorsetstatearray-map

TypeError: Cannot read property 'map' of undefined (axios => getData =>setState => .map => return elmItem => error)


Should I use pagination? Whenever I click this button <Delete> its throw out

TypeError: Cannot read property 'map' of undefined.

Is there any related between

axios => getData =>setState => .map => return elmItem

Thank you!

class ContentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
    };
  }

  componentDidMount() {
    axios
      .get("http://localhost:4000/api/todos")
      .then(res => this.setState({ items: res.data.result }))
      .catch(error => console.log(error));
  }

  handleDelete = value => {
    axios
    .delete(`http://localhost:4000/api/todos/${value}`)
    .then(res => this.setState({items: res.data.result}))
    .catch(error => console.log(error));
  };

  render() {
    let { items } = this.state;
    const elmItem = items.map((item, index) => {
      return <TableComponent item={item} key={index} index={index} handleDelete={this.handleDelete}/>;
    });}
    <table className="table">
          <tbody>{elmItem}</tbody>
    </table>

Solution

  • Debug your handleDelete function with console.log(); in your console browser.

    1. Check your value parameter is pass the correct value.
    2. Check your response as well.
     handleDelete = value => {
        console.log(value); // check paremeter value here
        axios
        .delete(`http://localhost:4000/api/todos/${value}`)
        .then(res => {
          console.log(res.data.result) // check is data return in the array form so you iterate with the map function.
         this.setState({items: res.data.result})
        })
        .catch(error => console.log(error));
      };
    

    To learn more about the axios hit the below link

    https://github.com/axios/axios

    To understand about the map hit the below link

    https://reactjs.org/docs/lists-and-keys.html