0

I have to read a json file, I followed the following code: stackoverflow

Trying the example shown in the comment, but it's not working for me.

I have to read this file that I have locally, but I'm not succeeding.

Can you give me a hand?

Link: Codesandbox

Code:

fetch("/user.json")
  .then(res => res.json())
  .then(res => res.results)
  .then(res => {
    console.log(res);
    let u = res.map((suggestion, i) => ({
      label: suggestion.email,
      name: suggestion.name.first,
      surname: suggestion.name.last,
      address: suggestion.location.street.name,
      email: suggestion.email,
      picture: suggestion.picture.thumbnail
    }));
    let options =
      inputLength === 0
        ? []
        : u.filter(suggestion => {
            const keep =
              count < 5 &&
              suggestion.label &&
              suggestion.label.slice(0, inputLength).toLowerCase() ===
                inputValue;
            if (keep) count += 1;
            return keep;
          });
    this.setState({ options });
  })
  .catch(e => console.log("Er:", e));
Paul
  • 3,644
  • 9
  • 47
  • 113
  • What's the problem? What's happening right now? What's the expected behaviour? – Emile Bergeron Oct 16 '19 at 14:09
  • I would like to read the file. He does not read it and enters the fetch catch condition. But if you try the example I posted on codesandbox, you see it immediately. – Paul Oct 16 '19 at 14:13
  • Where is the user.json file ? If it's in the public folder, the fetch uri param should be `${process.env.PUBLIC_URL} + "/user.json"` Actually i tried your CodeSandbox demo, and it works; but it doesn't in your local environment ? – JeanSaigne Oct 16 '19 at 14:14
  • I have already tried printing the process.env.PUBLIC_URL returns undefined. – Paul Oct 16 '19 at 14:17
  • Please update your question description. – Emile Bergeron Oct 16 '19 at 14:19

1 Answers1

0

You can just use import or require as follows:

const data = require("./myFile.json")
import data from "./myFile.json"