K
K
Kappy2018-11-26 12:06:47
JavaScript
Kappy, 2018-11-26 12:06:47

How to do fetch in react?

Good afternoon, I get json from the server, I process it, but the render call occurs 2 times.
Googled, make an empty object in the constructor. And if the object does not have a property, then undefined is returned, but I also have arrays, because of which the application falls.
I am attaching the code. How do you get the data out of the state? Really fetch in render and write?

export default class Forma extends React.Component {

    constructor(props) {
        super(props);
        this.state ={data:[]}
    }

    componentWillMount(){

        fetch('http://localhost:3001')
            .then(response => response.json())
            .then(result => this.setState({data: result}))
            .catch(e => console.log(e));
    }



    render() {
        const { data } = this.state;


        return <h1>{console.log(data.goals[0].gs_id)}</h1> //падает 
}


}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-11-26
@KappyJS

1. It is considered bad manners to use such unsafe constructs. 2. Use the boot state key in state.data.goals[0].gs_id

export default class Forma extends React.Component {
    constructor(props) {
        super(props);

        this.state ={ data: {}, isFetching: true, error: null };
    }

    componentDidMount() {
        fetch('http://localhost:3001')
            .then(response => response.json())
            .then(result => this.setState({data: result, isFetching: false }));
            .catch(e => {
              console.log(e);
              this.setState({data: result, isFetching: false, error: e }));
            });
    }

    render() {
        const { data, isFetching, error } = this.state;
        
        if (isFetching) return <div>...Loading</div>;

        if (error) return <div>{`Error: ${e.message}`}</div>;

        return <h1>{data.goals[0].gs_id}</h1>;
    }


}

B
Boris Cherepanov, 2019-02-05
@xakplant

or like this

import React, { Component } from 'react';

class Succes extends Component{
    constructor(props){
        super(props);
        this.state = { error: null,
            isLoaded: false,
            items: Array
        }
    }



    componentDidMount() {
        // Fetch тут
        fetch("http://example.url/page.php")
            .then((response) => response.json())
            .then((response) => {
                    this.setState({items: response});
                    this.setState({isLoaded: true});
            })
            .then((error) => {
                this.setState({false: true});
                this.setState({error});
            })


    }



    render (){
        const data = Array.from(this.state.data.headers);

    }

}

export default Succes;

Well, you can read the details here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question