Jason Chen
Jason Chen

Reputation: 2577

How to have multiple instances of getInitialState in Reactjs?

This is my code in React. I have multiple instances of getInitialState for different functions. However, I am finding that there may be a problem with getting them all to run this way.

getInitialState: function(){
if (localStorage.getItem('something'))
{return {signedin: true}}
else {return {signedin: false}}
},

getInitialState:function(){
return {error: true}
},

getInitialState:function(){
return {fliphouse: false}
},

To explain, the second instance of getInitialState, as is, does not work. That is, unless, I flip the order of the second and third getInitialState. When I do that, the code runs as it should. But I get the feeling React is trying to tell me something.

Is this normally the way to organize React code within a component?

Upvotes: 0

Views: 367

Answers (2)

chardy
chardy

Reputation: 1253

You can define them all in the same object:

getInitialState() {
  return {
    signedIn: !!localStorage.getItem('something'),
    error: false,
    fliphouse: false
  };
}

You can change them individually anywhere in the component (except in the render() function), e.g.:

this.setState({ error: true }) // causes a new render

Upvotes: 3

Harkirat Saluja
Harkirat Saluja

Reputation: 8114

This is not the correct way to put the initial state of the component. Initial state function is called only once when you component is about to mount; over here you set the state of the component(what variables or object properties you need) and then update them accordingly using setState in other methods like componentDidMount etc..

So in your question I would say put all 3 variables signedIn, error and fliphouse in the state object and then update this object. So a single initialState function would do.

Upvotes: 1

Related Questions