Mohammed Sabir
Mohammed Sabir

Reputation: 167

Cannot read property 'setState' of undefined n fetch method of reactjs

I am using google contact api for fetching the contact.

In fetch method's response I am getting all the contacts. But While setting the state using setState its giving an error of Cannot read property 'setState' of undefined. Here is my code.

I had also gone through tutorials for his but not able to find the extact issue in this.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';


class App extends Component {
    constructor(props) {
        super(props)
        this.auth = this.auth.bind(this);
        this.state = {
            userarray: []
        }

    }
    auth() {
        var config = {
            'client_id': 'my-client-id',
            'scope': 'https://www.google.com/m8/feeds'
        };
        window.gapi.auth.authorize(config, function () {
            alert("Dd")
            // this.fetchtt(window.gapi.auth.getToken());  
            fetch("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + window.gapi.auth.getToken().access_token + "&max-results=700&v=3.0", {
                method: 'GET'
            })
                .then((result) => {
                    result.json().then((result) => {

                        // display all your data in console
                        console.log(result.feed);
                        result.feed.entry.map((entry, index) => {

                            console.log(entry.title.$t)
                            const user = [
                                name => entry.title.$t
                            ]
                            this.setState({
                                userarray: "ss"
                            });
                        })
                    })
                }
                )

        });
    }





    render() {
        return (
            <div className="App">
                <header className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <h1 className="App-title">Welcome to React</h1>
                </header>
                <p className="App-intro">
                    To get started, edit <code>src/App.js</code> and save to reload.
        </p>
                <button onClick={() => this.auth()}>GET CONTACTS FEED</button>
            </div>
        );
    }
}

export default App;

Upvotes: 0

Views: 348

Answers (1)

nanobar
nanobar

Reputation: 66315

window.gapi.auth.authorize(config, function () { will change the context in the callback use window.gapi.auth.authorize(config, () => { instead.

PS you don't need to nest your then -

.then(result => result.json())
.then(result => { ... })

Upvotes: 2

Related Questions