Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing state in react

I have a function:

    getCommits: function() {
    fetch('/commits').then((response) => {
        if (response.status >= 400) {
            throw new Error("Bad response from server");
        }
        return response.json();
     })
     .then((commits) => {
       this.setState({commits: commits});
     });
  },

I set the state in this function and now I want other functions to access this state. How can I do this?

this.state.commits was one idea I had.

     getTodaysCommits: function(){
     fetch('/commits').then((response) => {
        if (response.status >= 400) {
            throw new Error("Bad response from server");
        }
        return response.json();
     })
     .then((commits) => {
       var todaysCommits = [];
       for (var i = 0; i < commits.length; i++) {
         var today = new Date().toDateString();
         var stringToDate = new Date(commits[i].commit.author.date).toDateString();
         if (today == stringToDate){
           todaysCommits.push(commits[i])
         }
       }
       return todaysCommits;
     })
     .then((todaysCommits) => {
       this.setState({commits: todaysCommits});
     })
  },

In this function how can I use commits without having to fetch it from api and just use the state set in the previous function?

componentDidMount: function() {
    this.getCommits();}

I have my function that gets set on componentDidMount

like image 882
The worm Avatar asked Feb 13 '26 13:02

The worm


1 Answers

First you need to make sure that your state is set and then you can access it by referring to the context state as this.state.commits.

You need to make sure you are referring to the correct context.

Use it in the function as

getTodaysCommits: function(){

    var commits = this.state.commits;
    console.log(commits);

}
like image 178
Shubham Khatri Avatar answered Feb 16 '26 01:02

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!