0

I have a structure of src/resource/file.json.enter image description here

1.By installing load-json and using require:

    class App extends Component{  

      constructor(props) {
            super(props);
            this.state = {summaryData: [], sortBy: null};
            this.sortContent = this.sortContent.bind(this);
            }
         componentWillMount() {

            require('../resource/file.json')
                  .then(response => {
                    // Convert to JSON
                    return response;
                  })
                  .then(findresponse => {
                    // findresponse is an object
                    console.log(findresponse);
                    this.setState({summaryData: findresponse});
                  })
                  .catch(norespone => {
                    console.log('Im sorry but i could not fetch anything');
                  });
              }

And appears the message : Module not found: Can't resolve '../resource/file.json' in 'C:\Xampp\htdocs\path\to\app\src\pages'

  1. Through myJSON:

    request('https://api.myjson.com/bins/{id..}').then(sumres => {
      if (sumres) {
        this.setState({summaryData: sumres});
        console.log(this.state.summaryData);
      }
    });
    

    }

But nothing appears in the console or the network tab. Cans someone propose a solution? Is it possible to load the json file without installing a local server?

Sokratis V
  • 101
  • 2
  • 4
  • 15

1 Answers1

1

Yes! It is possible to load JSON into your page. At the top of script where you import your modules, import your json file.

Example:

import React from 'react';
import jsonData from '../resource/file.json';
etc...

And in your case, if you're trying to set it to state, just set the state when the component initializes.

constructor(props) {
    super(props);
    this.state = {
        summaryData: jsonData.myArray, 
        sortBy: null
    };

    this.sortContent = this.sortContent.bind(this);
}

Hope this helps!

MEnf
  • 1,482
  • 1
  • 12
  • 18
  • Thank you. Two observations a)the json file begins and ends { . . .. } so i want to load all the json file into the summaryData array. b)my component will change depending on the users choices, i don't know if it's the appropriate way to set state in the constructor (the component might have to be stateless) – Sokratis V Feb 19 '18 at 15:02
  • JSON stands for JavaScript Object Notation. JSON is (by nature) an object. I'm assuming you want to convert it into an array? That is a whole seperate issue, but there's many solutions on the net that can help you such as this one: https://stackoverflow.com/questions/45539619/react-convert-props-objects-into-array-then-setstate – MEnf Feb 19 '18 at 15:11
  • As for user's changing state, that's the wonderful thing about reactjs is that state can be changed and still remain pure. If a user is changing an input or some other piece of data, just use `this.setState({ summaryData: newData })` and the data will be overwritten with new data from the user. Although it's on you to shape the new state for the user based on their input but make sure to do so without mutating the current state. https://reactjs.org/docs/state-and-lifecycle.html – MEnf Feb 19 '18 at 15:14
  • you are very informative thank you, i read about turning the JSON into an array with `Object.values()` but still will not show the array in the console`var sumData = Object.values(jsonData); this.setState({summaryData: sumData});` – Sokratis V Feb 19 '18 at 15:37
  • Try this and let me know if it still wont show: `var sumData = Object.values(jsonData);this.setState({summaryData: sumData}, console.log(this.state.summaryData); ` Also, make this call inside the componentWillMount lifecycle hook please. – MEnf Feb 19 '18 at 15:43
  • Also, another thing to keep in mind is that using object.values will only copy the key of your object into the array. If your object is deeply nested, this might not be the correct solution for you. Also, I'd appreciate if you could check the answer as correct if this helped you. – MEnf Feb 19 '18 at 15:44
  • It shows the following : `0 __proto__ : Array(0) concat : ƒ concat() constructor : ƒ Array() copyWithin :` An empty array i guess, also i have checked for validation of the JSON file and it passes it. – Sokratis V Feb 19 '18 at 15:47
  • Hmmm.... In your componentWillMount hook, does simply console.logging your jsonData retrieve the correct data? – MEnf Feb 19 '18 at 15:56
  • yes now it works it shows in console the array.. an issue with the setState probably? – Sokratis V Feb 19 '18 at 16:01
  • I have another request and use setState like this: `componentWillMount() { request('http://...').then(res => { if (res) { this.setState({callerData: res}); } }); var sumData = Object.values(jsonData); this.setState({summaryData: sumData}); console.log(jsonData); }` – Sokratis V Feb 19 '18 at 16:07
  • It's probably not an issue with setState, unless it's being invoked wrong. Can you show my an example of what your JSON object structure looks like? – MEnf Feb 19 '18 at 16:11
  • Also, you really don't want to use the componentWillMount hook to make http requests, you should make them in componentDidMount and have some sort of loader to let the user know the data is loading. Check this article out for reference. https://daveceddia.com/where-fetch-data-componentwillmount-vs-componentdidmount/ – MEnf Feb 19 '18 at 16:12
  • `{ "impact": { "percent_value": 85, "label": "...", "message": "...", "absolute_value": 104 }, "title": "....", "highlights": { "highlight_1": { "duration": "0:00:00", "playback": "https://...", "id": "call-1", "title": "...." }, "highlight_2": { "duration": "0:00:00", "playback": "https://...", "id": "call-2", "title": "Happiness 80%" } } }` – Sokratis V Feb 19 '18 at 16:14
  • I'm not sure if it's good practice to call setState twice in the same function. I'd suggest trying this: `componentWillMount() { request('http://...').then(res => { if (res) { this.setState({callerData: res, jsonData: Object.values(jsonData)} } })}` ...or something, it's hard to format these things in the comment section lol – MEnf Feb 19 '18 at 16:16
  • i guess in the jsonData: .. i should put the summaryData and it shows 'summaryData' is not defined no-undef. It has been set in the constructor like this: `this.state = {callerData: [], summaryData: [], sortBy: null};` – Sokratis V Feb 19 '18 at 16:17
  • Yeah, Object.values won't work if your object is nested. Try using this method: https://stackoverflow.com/questions/34280216/how-to-convert-nested-object-to-array-of-objects-in-javascript – MEnf Feb 19 '18 at 16:18
  • i changed to this `componentDidMount() { var sumData = [], keys = Object.keys(jsonData); for (var i = 0, n = keys.length; i < n; i++) { var key = keys[i]; sumData[key] = jsonData[key]; } console.log(sumData); console.log(jsonData); request('http://..').then(res => { if (res) { this.setState({callerData: res, summaryData: sumData}); } });` and appeared this error TypeError: Cannot read property 'playback' of undefined (for a child component that uses props.callerData -sumData has [..] compared to jsonData – Sokratis V Feb 19 '18 at 16:32
  • I'm sorry man, but this is starting to go a bit outside of the scope of what I can help with. I'm having trouble following you over the comment section. Perhaps you can open a new issue in regards to this now that you know how to get json data into your react app. – MEnf Feb 19 '18 at 16:41
  • 1
    So the problem was that i wasn't calling the : `this.state.summaryData`, in the console.log. It passes the data to the state normally! Thank you very much for your help! – Sokratis V Feb 19 '18 at 17:39