A
A
Alexander Grimashevich2019-03-26 19:29:59
React
Alexander Grimashevich, 2019-03-26 19:29:59

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'));
}

I am sure that an experienced developer will understand in a second what the problem is and will tell you. The point is that by /api/all-calcs we get an array with posts. They need to be written to this.state.calcs so that they can be used in the getCalcs method.
Please help me figure out what I'm doing wrong.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hzzzzl, 2019-03-26
@jams

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() }

B
bugagashnik, 2019-03-26
@bugagashnik

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 question

Ask a Question

731 491 924 answers to any question