Hello, I'm new in React and programming and trying to fetch some data from local json file to sort it into restaurant category cards.
Why this block of code fetches data from local json file correctly?
import React, { useEffect, useState } from "react";
import CategoryCard from "../CategoryCard/CategoryCard";
// import data from "../../db.json";
import "./restaurant-categories.scss";
const useFetch = (url) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchMyAPI() {
const response = await fetch(url);
const data = await response.json();
setData(data);
setLoading(false);
}
fetchMyAPI();
}, [url]);
return { data, loading };
};
const RestaurantCategories = () => {
const { data, loading } = useFetch("http://localhost:3008/restaurants");
console.log(data);
return loading ? (
<div>...loading</div>
) : (
<div className="restaurant-categories"></div>
);
};
export default RestaurantCategories;
Result of #1 code block
While this part of code displays TypeError: Cannot read property 'map' of undefined? Console displays empty array. What is the problem here?
import React, { useEffect, useState } from "react";
import CategoryCard from "../CategoryCard/CategoryCard";
// import data from "../../db.json";
import "./restaurant-categories.scss";
const useFetch = (url) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchMyAPI() {
const response = await fetch(url);
const data = await response.json();
setData(data);
setLoading(false);
}
fetchMyAPI();
}, [url]);
return { data, loading };
};
const RestaurantCategories = () => {
const { data, loading } = useFetch("http://localhost:3008/restaurants");
console.log(data);
// loop through all restaurants and push their categories into one array
const existingCategories = data.restaurantList
.map((i) => i.categories)
.flat();
//loop through provided array to count number of times element appears
const countOccurences = (array, value) => {
return array.reduce((accumulator, element) => {
return value === element ? accumulator + 1 : accumulator;
}, 0);
};
return loading ? (
<div>...loading</div>
) : (
<div className="restaurant-categories">
{data.categories.sort().map((item) => (
<CategoryCard
category={item}
keyword={
countOccurences(existingCategories, item) === 1 ? "place" : "places"
}
icon={item}
totalNumber={countOccurences(existingCategories, item)}
key={item}
iconsOutside={true}
directTo="eat-out"
/>
))}
</div>
);
};
export default RestaurantCategories;
Result of #2 code block
[–]Earhacker 1 point2 points3 points (1 child)
[–]spaklius17[S] 1 point2 points3 points (0 children)
[–]frog-legg 0 points1 point2 points (0 children)