So here's the code, I simply want to use axios to get, then set that response to the state. Using ES6 arrow functions
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
class FieldValues extends Component {
constructor (props){
super(props);
this.state = {
todos: []
}
}
componentDidMount() {
axios.get(`127.0.0.1:8000/api/todos/`)
.then(res => {
this.setState({res.data});
});
}
render(){
console.log(this.state);
}
}
export default FieldValues;
Here's a browser screenshot from my local host serving up json via express and node.
And my error - Is it sad to admit that I've been at this for hours now?
Failed to compile.
Error in ./src/App.js Syntax error: Unexpected token, expected , (15:26)
13 | axios.get(`127.0.0.1:8000/api/todos/`)
14 | .then(res => {
> 15 | this.setState({res.data});
| ^
16 | });
17 | }
18 |
Error
@ ./src/index.js 13:11-27
I'm guessing what you're getting back from your API is an array of ToDos. In that case, you need this:
The
setState
call takes in an object. When creating an object, you need to give each property a name and a value. The way you're doing it, you're not giving your property a name. Perhaps you've seen code like this and that's causing confusion:The reason THAT works is because in ES6 they added a feature where if your variable name also happens to be the name you want as your property name, you can omit the
{name: name}
duplication. In your case however, A) it's a nested property ofres
so that trick wouldn't work, and B) you want it to be calledtodos
.