I am making a simple AJAX request with the fetch API in React, specifically in the componentDidMount() function.
It is working, because the console appears to be logging the result. However, I don't know how to access the response...
componentDidMount = () => {
let URL = 'https://jsonplaceholder.typicode.com/users'
fetch(URL)
.then(function(response) {
let myData = response.json()
return myData;
})
.then(function(json) {
console.log('parsed json', json)
})
.catch(function(ex) {
console.log('parsing failed', ex)
})
} // end componentDidMount
I tried accessing myData outside of the fetch method, but this throws an error saying that it is undefined. So it is only accessible within the scope of the function.
I then tried this:
.then(function(response) {
let myData = response.json()
// return myData;
this.setState({
data: myData
})
})
This time, I get Cannot read property 'setState' of undefined(…)
How do I pass the fetch response to the state, or even just a global variable?
UPDATE
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: null
}
}
componentDidMount() {
let URL = 'https://jsonplaceholder.typicode.com/users'
fetch(URL)
.then( (response) => {
let myData = response.json()
// return myData;
this.setState({
data: myData
})
})
.then( (json) => {
console.log('parsed json', json)
})
.catch( (ex) => {
console.log('parsing failed', ex)
})
console.log(this.state.data)
} // end componentDidMount
render() {
return (
<div className="App">
{this.state.data}
</div>
);
}
}
export default App;