T
T
Tash1moto2018-03-11 17:23:58
JavaScript
Tash1moto, 2018-03-11 17:23:58

What are the ways to correctly load data into a react component?

Tell me how to load the data correctly so that the component is re-rendered after the data is loaded, without using forceUpdate and not substituting blanks into the state

import React from 'react'
import { render } from 'react-dom'
import axios from 'axios'
import "bootstrap/scss/bootstrap.scss"



class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {data:null} // неработает ошибка, нету 0 индекса
        // this.state = {data:[{title:"placeholder title"}]} // работает с такой болванкой, данные ререндятся после фетча данных
        this.loadData()
    }

    loadData(){
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then(res=>{
                console.log("axios res data: ",res.data);
                this.setState({data:res.data})
            })
    }
    render() {
        return (
            <div>
            <h4>App component</h4>
            {this.state.data[0].title}
            </div>
        )
    }
}

render( 
    <div className = "container">
        <App/>
    </div>,
    document.getElementById("root")
)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-03-11
@Tash1moto

In general, the use of constructs like: in render is very bad style. Avoid it if possible. To make the component render the data loading field:

render() {
  const { data } = this.state;
  const isAllDataReady = data && data.length > 0;

  return (
    <div>
       {!isAllDataReady && <Preloader />}
       {isAllDataReady && (
         <div>
           <h4>App component</h4>
           {data[0].title}
         </div>
       )}
    </div>
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question