denskiz
denskiz

Reputation: 161

React - Cannot read property 'state' of undefined

I keep getting this error despite using a fat Arrow function the bind the context of this when using setState. Can anyone please help?

export default class App extends Component {

constructor(props) {
    super(props);
    this.state = {
        query: '',
        items: [],
        repos: []
    };
}

search(term) {
    this.setState({
        query: term
    });
    const clientId = '12489b7d9ed4251ebbca';
    const secret = 'ff53ac9a93aaa9e7cddc0c009d6f068302866ff2';

    function fetchUser() {
        return axios.get(`https://api.github.com/users/${this.state.query}/repos?client_id=${clientId}client_secret=${secret}`);
    }

    function fetchRepos() {
        return axios.get(`https://api.github.com/users/${this.state.query}?client_id=${clientId}client_secret=${secret}`);
    }

    axios.all([fetchUser(), fetchRepos()])
        .then(axios.spread((items, repos) => {
            this.setState({
                items: items.data,
                repos: repos.data

            });
            console.log(state);
        }));

}

Upvotes: 0

Views: 3321

Answers (3)

Andrii Starusiev
Andrii Starusiev

Reputation: 7774

If an error from fetchUser i think you have correct this in search function. So you need to bind fetchUser and fetchRepos:

const fetchUser = () => {
        return axios.get(`https://api.github.com/users/${this.state.query}/repos?client_id=${clientId}client_secret=${secret}`);
    }

Or

const fetchUser = function(){
        return axios.get(`https://api.github.com/users/${this.state.query}/repos?client_id=${clientId}client_secret=${secret}`);
    }.bind(this);

And the same for fetchRepos.

Upvotes: 0

webdeb
webdeb

Reputation: 13211

setState is not synchronous. If you want to use the value of the state after setting it, you have to provide a callback inside setState after the object.

This is how I would do it:

onSearch(term) {
  this.setState({ query: term }, () => {
    console.log(this.state.query);
    this.search();
  });
}

search() {
  // now you can be sure, that this.state.query is set and use it.. 

  // Use arrow functions, as they will reuse the parent scope.
  const fetchUser = () => {

  }
}

Upvotes: 0

MatTheWhale
MatTheWhale

Reputation: 977

From the error message it seems clear that this is undefined. This is probably because you are using it in search() and search() isn't bound to the component, making this completely meaningless. To fix this try adding this line at the end of your constructor function:

        this.search = this.search.bind(this);

Now you should be able to use this in your search function.

Upvotes: 3

Related Questions