Answer the question
In order to leave comments, you need to log in
How to write query result to React state?
Good evening.
I spend half a day in order to write the result of the request into the state of React.
Whole code:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
export default class AllCalcs extends Component {
constructor (props) {
super(props);
this.state = {
calcs: []
};
this.listItems = '';
this.fetchData();
this.getCalcs();
}
fetchData() {
axios.post('/api/all-calcs')
.then(response => this.setState({calcs: response.data}))
.catch(error => console.log(error));
}
getCalcs() {
this.listItems = this.state.calcs.map((calc, index) =>
<a key={index} href="#" className="list-group-item list-group-item-action flex-column align-items-start">
<div className="d-flex w-100 justify-content-between">
<h5 className="mb-1">{calc.h1}</h5>
<small>3 days ago</small>
</div>
<p className="mb-1">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget
risus varius blandit.</p>
<small>Donec id elit non mi porta.</small>
</a>
);
}
render() {
return (
<div>
<div className="list-group">
{this.listItems}
</div>
</div>
);
}
}
if (document.querySelector('#all-calcs')) {
ReactDOM.render(<AllCalcs />, document.querySelector('#all-calcs'));
}
Answer the question
In order to leave comments, you need to log in
Move the fetchData call to componentDidMount, and the getCalcs call to the render before the return, provided that the calcs in the state are already filled, like if (this.state.calcs.length) { this. getCalc() }
Can you elaborate on what stage is the problem? Is the request in progress? Successfully? The date comes from the request?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question