So I quite new to this. I want to load a external json file into react, and then use it.
The problem apparently is that the json hasn't been yet loaded, so I get errors. Like Cannot read property 'map' of undefined etc. The console.log give:
1 3 Uncaught TypeError: Cannot read property 'map' of undefined So I've read this has to do with asynchronous things. But I can't find any example on how to fix it. Or how to make it work.
I would really appreciate it to see a small example like this, to make it work.
Later on I want to make it possible to filter the json with <input type=text etc> with some kind of dynamic search. But first things first. So can someone help me out?
This is my simple file:
import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor(){ super(); this.state = { data: [] }; console.log('1'); }; componentDidMount() { fetch("http://asite.com/file.json") .then( (response) => { return response.json() }) .then( (json) => { this.setState({data: json}); console.log('2'); }) }; render() { console.log("3"); return( <div className="Employee"> { this.state.data.employees.map(function(employee) { return ( <div> <h1> {employee.name} </h1> </div> ) }) } </div> ) } } export default App;