NSsem
NSsem

Reputation: 71

React native modifying the same state at the same time

i'm just beginning to learn a bit of react native, i'm trying to make a simple cookie clicker app. when i click on my cookie the cookiecount goes up by 1, but i want the cookie count to go up by 1 every second too. when i click on the cookie a lot and the cookiecount flips out and jumps to differen numbers and back again, i think it has to do with me updating the cookiecount state 2 times at the same time?

export default function App(props) {
  {/* Make the state that holds the amount of cookies */}
  const [cookieCount, modifyCookieCount] = useState(0)
  const [costCount, modifyCostCount] = useState(10)
  const [perClickBoost, setBoost] = useState(1)
  const interval = setInterval(() => modifyCookieCount(cookieCount+1), 1000);

function addPurchase(count){
    modifyCookieCount(cookieCount-count)
    modifyCostCount(costCount+10);
    setBoost(perClickBoost+1)
  }
  
  return (
    <View style={styles.container}>
      <Text>{cookieCount}</Text>
      {/* TouchableOpacity is needed to make use of Onpress prop */} 
      <TouchableOpacity onPress = {addCookie}>
        <Image style={styles.image} source={require('./images/cookie.png')}/>
      </TouchableOpacity>
        <Purchasables addPurchase={addPurchase} count={cookieCount} title='Koekjesslaaf' cost={costCount}/>
      <StatusBar style="auto" />
    </View>
  );

  function addCookie(){
    {/* Add a cookie */}
    modifyCookieCount(cookieCount+perClickBoost)
  }

  
}

The issue rises from these two updates:

  const interval = setInterval(() => modifyCookieCount(cookieCount+1), 1000);

And

  function addCookie(){
    {/* Add a cookie */}
    modifyCookieCount(cookieCount+perClickBoost)
  }

I hope someone can help me out with this, i'm sorry if my code makes no sense, i just started learning.

Upvotes: 1

Views: 47

Answers (1)

JackDao
JackDao

Reputation: 513

My suggestion you can split to 2 variable for count cookie.

const [cookieAutoCount, modifyCookieAutoCount] = useState(0)
const [cookieTouchCount, modifyCookieTouchCount] = useState(0)

and what you need to do is check if cookieAutoCount + cookieTouchCount > limit reset both value check both two case each time auto increate and touch increate

Upvotes: 2

Related Questions