Mina Young
Mina Young

Reputation: 59

Cannot fetch data from json file

I wanna fetch the products from my products.json file and display it in my App.js by using map, but it doesn't work. Is there any way i can fix this? Btw thank you for helping me!

App.js:

import "./styles.css";
import { products } from "./data";

export default function App() {
  return (
    <div className="App">
      {products.map((product) => {
        return <div>products</div>;
      })}
    </div>
  );
}

data.json:

{
  products:
   [
    {
      id:1,
      img: "https://vcdn-vnexpress.vnecdn.net/2017/04/27/strawberry-2129-1493287309.jpg",
      title:"strawberry",
      price: 3
    },
    {
      id:2,
      img: "https://cdn.sallysbakingaddiction.com/wp-content/uploads/2012/01/mm-cookies.jpg",
      title:"cookies",
      price: 5
    },
    {
      id:3,
      img: "https://rangsua.vn/wp-content/uploads/2019/05/juice-bia.jpg",
      title:"juice",
      price: 7
    }
  ]
}
    
Sandbox link: https://codesandbox.io/s/cart-vjhfb?file=/src/data.json  

Upvotes: 0

Views: 279

Answers (2)

Mayur Vaghasiya
Mayur Vaghasiya

Reputation: 1472

You return the <div>products</div>, that's the problem. replace with <div>{product.title}</div>; code

Try this code it's working

import "./styles.css";
import { products } from "./data";

export default function App() {
  return (
    <div className="App">
      {products.map((product) => {
        return <div>{product.title}</div>;
      })}
    </div>
  );
}

Upvotes: 0

Parnab Sanyal
Parnab Sanyal

Reputation: 739

Two problems. (both likely to be silly mistakes)

  1. You want to use product variable, but you are using products
  2. You need to wrap product with {}. It will look like {product.title}

Upvotes: 1

Related Questions