简体   繁体   中英

Loading local JSON file in React for dynamic content

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"
}
]

在此处输入图像描述

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

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.

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM