Loading local JSON file in React for dynamic content

Viewed 4983

Im trying to figure out the best way of accessing the local JSON file and storing it in my current state. I hope i am in the right track :)

Project.js

import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";

// framer motion
import { motion } from "framer-motion";

const Project = (props) => {
const { projectID } = useParams();
const [project, setProject] = useState({});

  useEffect(() => {
    fetch('src/data/projects.json', {
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
      },
    })
      .then((res) => res.json())
      .then((data) => console.log(data));
  }, []);

  return (
    <motion.div exit={{ opacity: 0, transition: { duration: 1 } }}></motion.div>
  );
};

export default Project;

JSON FILE

[
{
  "title": "Example",
  "id": "1",
  "src": "example.png"
},
{
  "title": "Example 2",
  "id": "2",
  "src": "example-2.png"
}
]

enter image description here

3 Answers

This clearly looks like your relative path is not correct.

UPDATE: From the comments and cross checking it is clear that we must move our json file into a public folder for it to work.

So you need to first do that and directly use this path:

fetch('data/projects.json',

HERE IS THE DEMO: https://codesandbox.io/s/json-fanda-stydg?file=/src/App.js

I would use import to load json data and then use them.

To fetch data you need to upload your file in public folder. Then you can easily load that json data. Here is the link of working code.

Make sure you've uploaded your data inside public folder. Otherwise it won't work.

  const [projects, setProjects] = useState([]);

  const fetchJSONDataFrom = useCallback(async (path) => {
    const response = await fetch(path, {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      }
    });
    const data = await response.json();
    setProjects(data);
  }, []);

  useEffect(() => {
    fetchJSONDataFrom("data/projects.json");
  }, [fetchJSONDataFrom]);

Directly import json file (without using fetch).

import data from 'src/data/projects.json';

Stringify and parse data like this:

const loadedData = JSON.stringify(data);
const json = JSON.parse(loadedData);

Now you have json variable as valid array containing your data.

Related