Home > database >  Dynamically update value based on State in React
Dynamically update value based on State in React

Time:04-06

I have a react class based component where I have defined a state as follows:

class MyReactClass extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          selectedDataPoints: new Set()
        };
    }

    // This method is called dynamically when there is new addition of data
    storeData = (metricName, dataPoint) => {
        if (this.state.selectedDataPoints.has(dataPoint)) {
           this.state.selectedDataPoints.delete(dataPoint);
        } else {
           this.state.selectedDataPoints.add(dataPoint);
        }
    };
    
    render () {
        return (
            <p>{this.state.selectedDataPoints}</p>
        );
    }
}

Note that initially, the state is an empty set, nothing is displayed. But when the state gets populated eventually, I am facing trouble in spinning up the variable again. It is always taking as the original state which is an empty set.

CodePudding user response:

If you want the component to re-render, you have to call this.setState () - function.

CodePudding user response:

You can use componentshouldUpdate method to let your state reflect and should set the state using this.state({}) method.

CodePudding user response:

Use this code to set state for a set:

export default class Checklist extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedDataPoints: new Set()
    }
    
    this.addItem = this.addItem.bind(this);
    this.removeItem = this.removeItem.bind(this);
  }

  addItem(item) {
    this.setState(({ selectedDataPoints }) => ({
      selectedDataPoints: new Set(selectedDataPoints).add(item)
    }));
  }

  removeItem(item) {
    this.setState(({ selectedDataPoints }) => {
      const newSelectedDataPoints = new Set(selectedDataPoints);
      newSelectedDataPoints.delete(item);
      
      return {
       selectedDataPoints: newSelectedDataPoints
      };
    });
  }

  getItemCheckedStatus(item) {
    return this.state.checkedItems.has(item);
  }

   // This method is called dynamically when there is new addition of data
storeData = (metricName, dataPoint) => {
    if (this.state.selectedDataPoints.has(dataPoint)) {
       this.state.selectedDataPoints.removeItem(dataPoint);
    } else {
       this.state.selectedDataPoints.addItem(dataPoint);
    }
};

render () {
    return (
        <p>{this.state.selectedDataPoints}</p>
    );
}
}
  • Related