mindgrapes
mindgrapes

Reputation: 43

How do I increment a useState Object

const [counter, setCounter] = useState({seconds:0, minutes:0})

somehow i have difficulties to update these objects. i would like to call setcounter in an interval and update counter.minutes in an useEffect every 60s. but with each try my code gets more and more spaghetti :D

it is more of a general understanding/syntax problem i have. my main attempt looked like this:

 setCounter((counter)=> counter.seconds +1) 

or

setCounter((counter) => {...counter, second: second+1)

mby this helps displaying how i was trying to achieve the result –

Upvotes: 4

Views: 5393

Answers (3)

PhantomSpooks
PhantomSpooks

Reputation: 3570

I think you want take

setCounter( (counter) => ({...counter, second: second+1}));

and make it

setCounter( counter => ({...counter,seconds:counter.seconds+1 } ));

Upvotes: 5

Prayag Choraria
Prayag Choraria

Reputation: 819

Try this. I have created a component based on your requirement.

const Counter = () => {
    const [counter, setCounter] = useState({seconds:0, minutes:0});
    
    useEffect(() => {
        const interval = setInterval(() => updateCounter(), 1000);
        return () => {
            clearInterval(interval);
        };
    }, [])
    
    const updateCounter = () => {
        setCounter(counter => {
            let { seconds, minutes } = { ...counter};
            if(seconds === 59) {
                seconds = 0;
                minutes ++;
            } else {
                seconds ++;
            }
            return {
                seconds,
                minutes
            }
        });
    }

    return (
        <div>
            {JSON.stringify(counter)}
        </div>
    )
}

Upvotes: 1

Lautaro Zarandon
Lautaro Zarandon

Reputation: 290

You need to use function setInterval(()=>(), seconds), inside on useEffect.

src: https://dev.to/jarodpeachey/creating-a-countdown-using-react-hooks-58k

Countdown component

const {useState, useEffect} = React;

const Countdown = () => {
  const [countdownDate, setCountdownDate] = useState(new Date('12/25/2020').getTime());
  const [state, setState] = useState({
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0,
  });

  useEffect(() => {
    setInterval(() => updateCountdown(), 1000);
  }, []);

  const updateCountdown = () => {
    // TODO: Code to calculate how long between the countdown date and the current time
  };

  return (
    <div>
      <div className='countdown-wrapper'>
        <div className='time-section'>
          <div className='time'>{state.days || '0'}</div>
          <small className="time-text">Days</small>
        </div>
        <div className='time-section'>
          <div className='time'>:</div>
        </div>
        <div className='time-section'>
          <div className='time'>{state.hours || '00'}</div>
          <small className="time-text">Hours</small>
        </div>
        <div className='time-section'>
          <div className='time'>:</div>
        </div>
        <div className='time-section'>
          <div className='time'>{state.minutes || '00'}</div>
          <small className="time-text">Minutes</small>
        </div>
        <div className='time-section'>
          <div className='time'>:</div>
        </div>
        <div className='time-section'>
          <div className='time'>{state.seconds || '00'}</div>
          <small className="time-text">Seconds</small>
        </div>
      </div>
    </div>
  );
};

export default Countdown;

After create this component must be follow this

useEffect(() => {
  const tick = setInterval(() => setNewTime(), 60000); 
  return () => clearInterval(tick) 
}, []);

Upvotes: 0

Related Questions