4

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

15
  • Have you tried to console.log({res})? Maybe JSON itself is not in a valid format. Commented Jan 7, 2021 at 16:21
  • Can you try to remove comma after the second object? This is a stupid guess while I'm trying with the live code. Commented Jan 7, 2021 at 16:34
  • 2
    May i know why you are using fetch to load local json file? you can just import the json data normally using import Commented Jan 7, 2021 at 16:44
  • @SifatHaque : I don't see any problem fetching json data this way as well :) Commented Jan 7, 2021 at 16:49
  • @jmvdc check this article Unexpected token < in JSON at position 0 Commented Jan 7, 2021 at 16:50

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

10 Comments

typo my bad bro.
Could you show your pages directory image ?
Let me see Mate
This should technically work :) Can you create a sandbox for this one. And share the link with me... Or just to check it is working try removing header stuff from fetch...
fetch("./../data/projects.json'') .then(response => response.json()) .then(json => console.log(json));
|
2

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

5 Comments

But Technically that's not needed at all :) We can have data anywhere and we can fetch anytime :)
@ImranRafiqRather may be create react app is configured in such way. I'm not sure though.
Yup :) I checked it as well. It is working well with public folder
@jmvdc glad that it helps. Please don't hesitate to upvote or set this as accepted answer. May be this will help others as well :)
@ImranRafiqRather glad to hear that :)
1

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.

4 Comments

That's not needed at all. Even if this is done, then first we need to export the JSON data first :)
I already have a solution without using fetch but i'm trying to figure this out using promises
@ImranRafiqRather I was not exporting it. What do you mean by that? I created plain .json file (without creating a const and exporting it) with the data provided above and then just imported that file under the name of data. Maybe I'm making some cardinal mistake.
Ya your point is also valid... My bad. It's when we use .js extension in data. That we have to export it :)
-2

Make sure to use the full URL in your browser, such as: fetch('http://localhost:3000/your-json-file-name')

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
I don't think this answers the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.