Wiktor Kisielewski
Wiktor Kisielewski

Reputation: 437

Auto Update value in react component

I'm trying to build a component with auto-updating value based on cookies:

let cookies = 0;
(function count() {
cookies = document.cookie.split("?");
setTimeout(count, 10);
return cookies;
})();


class CartButton extends React.Component {
    state = {quantity: cookies.length}
    render() {
      return (
        <Cart onClick={e=>{show_cart()}}>
    <Mfont>{this.state.quantity}</Mfont>
    <Icon>shopping_cart</Icon>
    </Cart>
      );
    }
  } 

'count' function works as expected, component is rendered with the latest value returned. Unfortunately, it does not auto-update when 'cookies' are changed. It returns this error:

Warning: render(...): Replacing React-rendered children with a new root component. If you intended to update the children of this node, you should instead have the existing children update their state and render the new components instead of calling ReactDOM.render.

I have tried various variations here but still can't figure it out :/

Upvotes: 0

Views: 2339

Answers (2)

ravibagul91
ravibagul91

Reputation: 20755

componentDidMount will get execute only once when your component loads first time. This is the correct place to write any logic which we need to execute after page load.

Try this,

class CartButton extends React.Component {
    //It is good to have a constructor for the component which has state
    constructor(props){
      super(props);
      this.state = {quantity: cookies.length}
      this.updateQuantity;
    }

    componentDidMount(){
      this.updateQuantity = setInterval(()=> {
        cookies = document.cookie.split("?");
       this.setState({quantity: cookies.length})
      },10)
    }
    //Don't forget to clear any setInterval like below
    componentWillUnmount(){
       clearInterval(this.updateQuantity);
    }
    render() {
      return (
        <Cart onClick={e=>{show_cart()}}>
          <Mfont>{this.state.quantity}</Mfont>
          <Icon>shopping_cart</Icon>
        </Cart>);
    }
  } 

Upvotes: 2

Harish
Harish

Reputation: 1911

Here your CartButton is not updating even though count is working fine because CartButton is not listening to your cookies variable. React component updates only when there is either props or state change. You can something like this..

class CartButton extends React.Component {
    state = {quantity: cookies.length}

    componentDidMount(){
      setInterval(function count() {
        cookies = document.cookie.split("?");
       this.setState({quantity: cookies})
      }.bind(this), 10)
    }
    render() {
      return (
        <Cart onClick={e=>{show_cart()}}>
          <Mfont>{this.state.quantity}</Mfont>
          <Icon>shopping_cart</Icon>
        </Cart>);
    }
  } 

Upvotes: 1

Related Questions