@KappyJS

Как правильно делать fetch в react?

Добрый день, с сервера получаю json , обрабатываю его, но вызов render происходит 2 раза.
Гуглил, делают пустой обьект в конструкторе. И если у обьекта нет проперти, то возвращается undefined, но у меня есть и массивы, из за которых падает приложение .
Прикладываю код . Как все же вытащить данные из состояния? Неужели fetch в рендере и писать?
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> //падает 
}


}
  • Вопрос задан
  • 25083 просмотра
Решения вопроса 1
rockon404
@rockon404 Куратор тега React
Frontend Developer
1. data.goals[0].gs_id
Использование подобных, небезопасных конструкций считается плохим тоном.
2. Используйте в state ключ состояния загрузки.
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>;
    }


}
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
xakplant
@xakplant
Автор сайта xakplant.ru
Ну или так

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;


Ну подробно можете прочитать тут
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы