Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loading data from JSON in ReactJS

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading