Reputation: 11
I am new to React, and am trying to fill my components state with data stored on my mongodb Database.
I am using this call to fetch my data:
class DisplayPrograms extends Component {
constructor(props) {
super(props);
this.setState = { programs: [] };
}
componentDidMount() {
axios
.get("http://localhost:5000/programs")
.then((response) => {
console.log(response.data);
this.setState({ programs: response.data });
})
.catch(function (error) {
console.log(error);
});
}
render() { .....
My render() function (not included) is working, and my console.log(response.data) outputs an array of objects like it is supposed to as you can see below, but I keep getting the following error:
Array [ {…}, {…} ]
DisplayProducts.jsx:15
_________________________________________________
TypeError: "this.setState is not a function"
componentDidMount DisplayProducts.jsx:16
DisplayProducts.jsx:19
I'm sure it's a quick fix but I haven't been able to find a solution.
Upvotes: 0
Views: 42
Reputation: 574
In constructor
you need to create the initial state, so you need something like:
constructor(props) {
super(props);
this.state = {
programs: []
}
}
The this.setState
function you can use anywhere else.
Upvotes: 0
Reputation: 1651
Your constructor should look like this:
constructor(props) {
super(props);
this.state = { programs: [] };
}
You were using this.setState()
in the constructor instead of this.state
Here are the docs on this which show the syntax.
Upvotes: 3