Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React | TypeError: this.state.cars.map is not a function

I'm trying to show a list of car brands in react but i get this error. The Web API is tested and works fine.

TypeError: this.state.cars.map is not a function

import React from "react";
import axios from "axios";

export default class cars extends React.Component {
  state = {
    cars: []
  };

  async componentDidMount() {
    axios.get("http://localhost:3000/api/fetchcars").then(res =>{
        console.log(res);
        this.setState({cars: res.data});
    });
  }

  render() {
      return(
          <ul>
              {this.state.cars.map(car => <li>{car.brand}</li>)}
          </ul>
      )
  }
}

Response Output

config: Object { url: "http://localhost:3000/api/fetchcars", method: "get", timeout: 0, … }
data: {…}
car: Array(3) [ {…}, {…}, {…} ]
status: true
<prototype>: Object { … }
headers: Object { "content-type": "application/json; charset=utf-8" }
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
status: 200
statusText: "OK"
<prototype>: Object { … }
like image 983
Kaiison Avatar asked May 11 '26 21:05

Kaiison


1 Answers

This error will generally crop up because you're trying to map something that is not of the type array. Make sure you're actually mapping an array. If it is an array this crops up usually because the value you're expecting to map across is undefined or null. If that is the case, that is your problem, and you must check that the value exists before mapping it.

In this case you're targeting res.data which is an object, instead of the array which is res.car.

like image 126
William Park Avatar answered May 13 '26 12:05

William Park



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!