The worm The worm - 1 month ago 21
React JSX Question

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

Answer

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);

}
Comments