Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array of json from external file is not setting up the state in react

I am learning react. And I am trying to setState on componentDidMount() function with external file contains Array of Data but it is not setting up the state. It shows empty every time I refresh the page.

app.js

import './App.css';
import React from 'react';
import newData from './data.js';


class App extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            data : []
        }
    }

    componentDidMount() {
        this.setState({data: newData});
        console.log(this.state.data)
    }

    
    render(){
    return (
        <div>Hello</div>
        )
    }

}

data.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const newData = [
    {
      "id": 1,
      "name": "GoodName",
    },
]


export default newData

I have also tried by changing the format of data and wrap into a a Seed.function like

window.Seed = (function() {

    const newData = [
        {
            id: 1,
            name: 'GoodName',
        },
    ];
    return {newData: newData };
}());

And tried to setState by

this.setState({data: Seed.newData});

But it says, Seed is not defined

  • Should I need to import external json array file in index.html instead of App.js ?

  • Should I need to use map function or for of loop to iterate every element in data before setting state ?

I have tried many times but it is still not working.

Any help would be much Appreciated. Thank You in Advance.

>Solution :

this.state.data is not immediately available after calling setState. Check:
https://reactjs.org/docs/faq-state.html#why-doesnt-react-update-thisstate-synchronously

Try to stick console.log in render instead to see the contents of an array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading