Im trying to mock a Plant API by using a db.json file (relative path: src\plant-api\db.json), and passing it from the parent component (ItemList) to its child (Item) but its not working because i see no data displayed on screen even tho i can see it in my console.log. Heres the full code
import React, { useState, useEffect } from "react";
import Item from "./Item";
import Data from "../plant-api/db.json"
const ItemList = () => {
const [plants, setPlants] = useState([]);
useEffect(() => {
fetch(Data)
.then((response) => response.json())
.then((data) => setPlants(data));
}, []);
console.log(Data)
return (
<div className="items">
{plants.map((plant) => {
return (
<div>
<Item data={plant} />
</div>
);
})}
</div>
);
};
export default ItemList;
import React from "react";
import ItemCount from "./ItemCount";
const Item = ({ data }) => {
return (
<div>
<div className="item">
<img src={data.pic} alt="plant-image" />
<h3>{data.name}</h3>
<p>{data.category}</p>
<h4>{data.price}</h4>
<ItemCount stock="10" initial="0" />
</div>
</div>
);
};
export default Item;
Any help is needed and appreciated!
CodePudding user response:
maybe you can use the json-server package, so you can create a dummy API,.
an example of using code like the one below in the terminal, make sure the code is run in the db.json file directory.
npx json-server db.json -p2000
later there will be a json server running as an API on port 2000
CodePudding user response:
fetch is used to make network calls, but since you have already have Data imported, you can just set the data in your useEffect hook: setPlants(Data);
This should be enough if you're just trying to see how the data renders.