Usestate not updating the state when trying to set state

Viewed 33

So I've been trying to build a timer app. When the user clicks on the button, it should update the state so that the countdown function gets triggered. So far it's not working but i notice that when i manually change the state, it works. Please i need help with this

enter image description here

 Countdown component:
 

    import React, { useState, useEffect, useRef } from 'react';
    import { View, Text, StyleSheet } from 'react-native';
    
    
    export const Countdown = ({ minutes = 20, isPaused }) => {
      const interval = useRef(null);
    
     function Minutetomilli(min) {
        return min * 1000 * 60;
      }
    
      const [milli, setMilli] = useState(Minutetomilli(minutes));
      
      function FormatTime(time) {
        return time < 10 ? `0${time}` : time;
      }
      const countdown = () => {
        setMilli((time) => {
          if (time === 0) {
            return time;
          } else {
            const timeleft = time - 1000; 
         
            return timeleft;
          }
        });
      };
    
         useEffect(() => {
        if (isPaused) {
          return;
        } else{
          interval.current = setInterval(countdown, 1000);
          return () => clearInterval(interval.current);
        } 
      }, [isPaused]);
      const minute = Math.floor(milli / 60000) % 60; 
      const seconds = (milli / 1000) % 60; 
    
      return (
        <Text style={Styles.text}>
          {FormatTime(minute)} : {FormatTime(seconds)}
        </Text>
      );
    };
    
    
    const Styles = StyleSheet.create({
      text: {
        fontSize: 70,
        fontWeight: 'bold',
        color: 'white',
        padding: 20,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
      },
    });

enter image description here

1 Answers

Try this

<View style={Styles.buttonwrapper}>
        
        <Button title={isStarted ? "pause": "start" } onPress{() => {setIsStarted(!isStarted)}} />
        
</View>

Rather than

<View style={Styles.buttonwrapper}>
        {isStarted ? (
        <Button title="pause" onPress{() => {setIsStarted(false)}} />
        ):(
        Button title="start" onPress{() => {setIsStarted(true)}} />
        )}
</View>

One thing that comes in my mind is that you are passing onPress function as prop. If I am correct then your approach is wrong. You can learn it here:

Can we pass setState as props from one component to other and change parent state from child component in React?

Related