Home > Net >  React JS Product display using axios
React JS Product display using axios

Time:07-13

Anyone please tell me what wrong in this code:

import React, { useEffect, useState } from "react";

import { Link } from "react-router-dom";

import axios from "axios";

function Shop() {

  const [items, setItems] = useState([]);

  const url = "https://dummyjson.com/products";


  useEffect(() => {

    axios.get(url).then((response) => {

      setItems(response.data);

      console.log(response.data);

    });

  });


  return (

    <div className="about-page">

      {items.map((item) => (

        <div>

          <h2 key={item.id}>

            Brand: <Link to={`/shop/${item.id}`}>{item.brand}</Link>

          </h2>

        </div>

      ))}

    </div>

  );

}


export default Shop;

Error is:

items.map is not a function

CodePudding user response:

you are setting an object instead of an array use this in useEffect

useEffect(() => {

axios.get(url).then((response) => {

  setItems(response.data.products);

  console.log(response.data);

  });

});

CodePudding user response:

Is the type of response data an array type? maybe it is not array

Or items?.map((item) => (.......

CodePudding user response:

this one help full for you pls find the working demo here link in index.js you need to add <BrowserRouter>.

index.js

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);
import React, { useEffect, useState } from "react";

import { Link } from "react-router-dom";

import axios from "axios";

function Shop() {
  const [items, setItems] = useState([]);

  const url = "https://dummyjson.com/products";

  const getData = async () => {
    const { data } = await axios.get(url);
    setItems(data);
  };

  useEffect(() => {
    getData();
    console.log(items.products);
  }, []);

  return (
    <div className="about-page">
      {items?.products?.map((item) => (
        <h2 key={item.id}>
          Brand: <Link to={`/shop/${item?.id}`}>{item?.brand}</Link>
        </h2>
      ))}
    </div>
  );
}

export default Shop;


  • Related