flix
flix

Reputation: 1974

React Native - can I set dynamic initial state?

let say I have a state like this:

constructor(props) {
  super(props);
  this.state = {
    FirstTime:
    {
      foo: 'ex1'
    }
  }
}

and then I setState the FirstTime to add another key/value:

this.setState({FirstTime: {...this.state.FirstTime, bar: 'ex2'}})

there's a way to change the initial state to be like this:

constructor(props) {
  super(props);
  this.state = {
    FirstTime:
    {
      foo: 'ex1',
      bar: 'ex2'
    }
  }
}

when I reloaded the apps?

Upvotes: 1

Views: 576

Answers (1)

Rajendran Nadar
Rajendran Nadar

Reputation: 5438

Try something like this

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      FirstTime: {
        foo: 'ex1'
      }
    }
  }

  render() {
    console.log(this.state.FirstTime); //Sorry a typo found in this line
    return (
      <div>Hey</div>
    );
  }

  componentDidMount() {
    let obj = {
      bar: 'ex2'
    }

    let finalData = { ...this.state.FirstTime, ...obj }
    
    this.setState({ FirstTime: finalData })
  }
}

const rootElement = document.getElementById("root")

ReactDOM.render(
  <App />,
  rootElement
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 1

Related Questions