varma.Mantena
varma.Mantena

Reputation: 37

How to initialize from setstate in Reactjs?

I am able to initialize setstate still the values are taking from state only

_handleClickFilter(value, xname, chartId){
    console.log("dataSourceId", this.state.dataSource);
    this.setState({
          filterData: [{
          filter: "equals",  
          value:value ,
          attribute:xname, 
        }]
        });

    let filterdefinitions = {
        dataSourceId : "59ef50d6e4b054efd6d8aa53",
        filterDefinitions: this.state.filterData,
      }

      let data = {
        filterDefinitions: [filterdefinitions],
      };
      DashboardAction._ApplicableFilterToDashboard(data, this.props.params.dashboardId);
      DashboardAction._ApplicableFilterToChart(data, this.props.params.dashboardId, chartId);
      DashboardAction._saveFilterToDashboard(data, this.props.params.dashboardId);


}

I am able to get values in the setstate which I want. But the values are not getting set. Showing the values exists in the this.state only.

thanks in advance

Upvotes: 0

Views: 597

Answers (2)

César Landesa
César Landesa

Reputation: 2656

setState is async, so it's not guaranteed that the state will be set after you have used it until the re-render is triggered. You should be very careful about using the state right after you have set it, a more 'reactive' approach is usually better. However, if you want to make sure that you'll be able to access the new state, you can use the second argument of setState which is a callback function that will be called when the state is set.

You can use it this way:

_handleClickFilter(value, xname, chartId){
    this.setState({
          filterData: [{
          filter: "equals",  
          value:value ,
          attribute:xname, 
        }]
    }, () => {

    let filterdefinitions = {
        dataSourceId : "59ef50d6e4b054efd6d8aa53",
        filterDefinitions: this.state.filterData,
      }

      let data = {
        filterDefinitions: [filterdefinitions],
      };
      DashboardAction._ApplicableFilterToDashboard(data, this.props.params.dashboardId);
      DashboardAction._ApplicableFilterToChart(data, this.props.params.dashboardId, chartId);
      DashboardAction._saveFilterToDashboard(data, this.props.params.dashboardId);

    });
}

Upvotes: 1

Abhishek Raj
Abhishek Raj

Reputation: 512

Replace your set state code with this

   this.setState({ 
        filterData: this.state.filterData.map((data, index) => {
        data.filter = "equals",
        data.value = value,
        data.attribute=xname
}) });

Upvotes: 1

Related Questions