简体   繁体   中英

Extracting data from GET request using axios

I am having an issue of extracting data from axios GET request. Below is my code:

const Product = () => {
  const [cars, setCar] = useState([]);
  useEffect(() => {
    const fetchPosts = async () => {
      const res = await axios.get("http://192.168.29.135:8000/data/cars");
      //console.log(res);
      setCar(res.data);
      console.log(typeof res.data);
      console.log(res.data);
      console.log(cars);
    };
    fetchPosts();
  }, []);

  return <div>{cars.car_name}</div>;
}

The output for console.log(res.data) is this:

 {status: 1, message: "Cars List", data: Array(30)}
    data: (30) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
    message: "Cars List"
    status: 1
    __proto__: Object

And the output for console.log(cars) is

Undefined

So, I am unable to use the map function which gives me the error 'Map is not a function. I think I need to use this setCar(res.data.data). But even that is not working. Where am I going wrong? Thanks for the help.

setCar is asynchronous so you can't get cars immediately after it is set, which is why you get undefined in the console.log .

However, cars are being set correctly to state, but because it's a list you can only map through it to be able to access the values.

Consider refactoring the useEffect to setCars only when data is available

useEffect(() => {
    const fetchPosts = async () => {
      const res = await axios.get("http://192.168.29.135:8000/data/cars");
      if (res.data) {
        setCar(res.data);
      }
    };
    fetchPosts();
  }, []);

So your return should return JSX like this

return (
      <div>
            {cars.map(car => 
                <span key={car.id}>
                  {car.car_name}
                </span>
            )}
       </div>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM