Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
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

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!