OunknownO
OunknownO

Reputation: 1196

What is the best practice when setting initial state if i use redux in react app

I'm trying to move app to redux(newbie). I have this code and I'm confused a little bit what is the best practice to set initial state. For example this is code

class App extends Component {

 constructor(props) {
  super(props);
  this.state = {
      cityName: '',
      nameOfCity:'',
      weatherDescription:'',
      windSpeed:'',
      temperature:'',
      maxTemperature:'',
      minTemperature:''
  };
}

updateInfo(results){
  this.setState({
      nameOfCity: results.city.name,
      weatherDescription: results.list[0].weather[0].description,
      windSpeed: results.list[2].wind.speed,
      temperature: results.list[0].main.temp,
      maxTemperature: results.list[0].main.temp_max,
      minTemperature: results.list[0].main.temp_min
  });
   }

render() {
return (
  <div className="App">
    <div className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h2>Weather App</h2>
    </div>
    <p className="App-intro">
      To get started, edit <code>src/App.js</code> and save to reload.
    </p>
      <FormContainer label="Name of the city:" updateInfo={this.updateInfo.bind(this)}/>
      <WeatherInfo
          nameOfCity={this.state.nameOfCity}
          weatherDescription={this.state.weatherDescription}
          windSpeed={this.state.windSpeed}
          temperature={this.state.temperature}
          maxTemperature={this.state.maxTemperature}
          minTemperature={this.state.minTemperature}
      />
  </div>
  );
}
}

And what is the best practice when you use redux

Upvotes: 0

Views: 542

Answers (2)

spirift
spirift

Reputation: 3062

When using Redux you shouldn't need to use react state in this way. As in all application data. All of this state should be moved to the central redux store and populated via actions and reducers. You then use the connect method of react-redux to map the store state to the props of the component.

For your app updateInfo should be an action creator and have a reducer which will reduce the form data sent in this action into the state. Because the redux state is mapped to the props of you component the view will update as you would expect by displaying this.props.weatherDescription or whatever data you like.

Have a look at the documentation here to get a fuller idea of how to structure a react redux app. There is also a video series on getting started with redux here

Upvotes: 1

Mohammad shaban
Mohammad shaban

Reputation: 251

first you need to setup redux in your app then set initial state in redux store Please go through this link

http://redux.js.org/docs/introduction/Examples.html

Upvotes: 1

Related Questions