Home > Net >  Loading data from JSON in ReactJS
Loading data from JSON in ReactJS

Time:09-20

I want to get data through a JSON file so data will be displayed on my app. I used to do it through a http link from firebase, but I want to do so I can call it from a path from my React-app. I've been searching, but got no luck finding helpful links.

import React, { useState, useEffect } from 'react';
import style from './AvailableMeal.module.css';
import Card from '../UI/Card';
import MealItem from './MealItem/MealItem';
//import Food from './food.json';

const AvailableMeal = () => {
  const [Meals, setMeals] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

useEffect(() => {
const fetchMeals = async() => {
  const response = await fetch('https://aaaaa.firebaseio.com/meals.json');
  //const response = await fetch(Food);
  //console.log(response);

  const data = await response.json();
  const loadedMeals = [];
  for(const key in data) {
    loadedMeals.push({
      id: key,
      name: data[key].name,
      description: data[key].description,
      price: data[key].price,
    });
  }
  setMeals(loadedMeals);
  setIsLoading(false);
}
  fetchMeals();
}, []);
 
  const mealsList = Meals.map((val) => (
    <MealItem id={val.id}
            key={val.id}
            name={val.name}
            description={val.description}
            price={val.price}
    />
  ));
  
  return (
    <>
     <section className={style.meals}>
     <Card>
     {isLoading ? <div className={style.loading}><p>Loading...</p> </div> : <ul>{mealsList}</ul>}
      </Card>
    </section>
    </>
  )
};

export default AvailableMeal;

What I thought I could do is to import to my JSON file in my project, and then call it in the parameter.

 import Food from './food.json';
 .....
 const response = await fetch(Food);

How can I do so, I go from http link to call it from my React-app path.

CodePudding user response:

Try to use just Food
like this

import Food from './food.json';
.....
console.log(Food);

You already has that json and access to it after import
You don't have to use fetch

  • Related