Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React + Fetch+ Json. TypeError: Cannot read property of undefined

When I used SuperAgent I didn't have this problem, but I decided to use Window.fetch polifyl and I met this problem. I see all data was loaded, but it still shows error. Could your help me identify this error please: Screen Shot

In render() I genereate a list of components based on an obtained list:

    render() {

    if (this.state.data.list) {
        console.log("render: " + this.state.data.list);
        var counter = 0;
        const list = this.state.data.list.map((item) => {
....
like image 697
Alex Pilugin Avatar asked Feb 17 '26 06:02

Alex Pilugin


2 Answers

The promise handlers in your screenshot won't work:

.then((json) => console.log('parsed json: ', json))
.then((json) => { this.setState({ data: json }); })

"Take the value from resolving this promise and pass it to console.log. Then, take console.log's return value (which is undefined) and pass it to this.setState."

like image 82
Josh Kelley Avatar answered Feb 19 '26 23:02

Josh Kelley


    fetch(url, {
        headers: {
            'Accept': 'application/json',
        },
    }).then((response) => response.json()
        .catch(err => {
            console.err(`'${err}' happened!`);
            return {};
        }))
        .then((json) => {
            console.log('parsed json: ', json);
            this.setState({ data: json })
        })
        .catch((err) => { console.log('fetch request failed: ', err) }
        )
like image 36
Alex Pilugin Avatar answered Feb 19 '26 23:02

Alex Pilugin