Home > Mobile >  unable to map as url is not an array // React Router
unable to map as url is not an array // React Router

Time:01-12

Hi I have a main page called FeaturedProduct.js which lists all the products fetch from the API https://fakestoreapi.com.

I trying to set up react router dom version (6) whereby user click on any of the product will open up that single product through Product.js

This is my code: https://codesandbox.io/s/magical-smoke-r7yik9?file=/src/Product.js

I having issues because I can't use the map function without errors. The error being `data.map' is a not a function (in Product.js)

Do I need to access further into the "api" json like data.x.map?

CodePudding user response:

Always check carefully the response you are getting from an api weather its object or an array.

i have modified your file, you can replace it with your original product.js component.

And always use ?. operator whenever you play with data that come from an api because useEffect hook will run after your component is loaded, hence it will give you an error that your data is undefined. It will not happen in your case you are getting only single object which is fast operation, but if you are getting larger data then you have to use ?. operator.

import React, { useState, useEffect } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";

// individual product
// functional component

const Product = () => {
  const [data, setData] = useState('); // set initial state (data) to an empty array
  const { id } = useParams();  

  useEffect(() => {
    axios
      .get(`https://fakestoreapi.com/products/${id}`) // change from ?id=${id} to ${id} because API url is .com/products/1  // But couldn't map due to not being array
      .then((res) => {
        setData(res.data);        
      })
      .catch((err) => console.log(err));
  }, []);
  return (
    <div>              
          <div className="product-container" key={data?.id}>
            <div>
              <img className="prod-image" src={data?.image} alt="" />
            </div>
            <div>
              <h1 className="brand">{data?.title}</h1>
              <h2>{data?.category}</h2>
              <p>{data?.description}</p>
              <p>
                <strong>Price:</strong> {data?.price}
              </p>
              <p>
                <strong>Rating:</strong> {data?.rating?.rate}
              </p>
            </div>
          </div>          
      <div className="back">
        <Link to="/">Feature Products</Link>
      </div>
    </div>
  );
};

export default Product;

  • Related