Home > Blockchain >  How to update state in React Native?
How to update state in React Native?

Time:07-16

I am trying to create a counter app where certain cards either 1 or -1. As each number on the keypad is clicked the counter increments 1 or -1. So far I've created a custom component and trying to update the state in order to count up or down

My code below is meant to be using the cards object to increment or decrement the count but for testing purposes I tried just creating a function to update state to see if I am using it correctly but it doesn't seem to be working?

export default function App() {

  const cards = [
    { card: "A", count: -1 },
    { card: "K", count: -1 },
    { card: "Q", count: -1 },
    { card: "J", count: -1 },
    { card: 10, count: -1 },
    { card: 9, count: 0 },
    { card: 8, count: 0 },
    { card: 7, count: 0 },
    { card: 6, count: 1 },
    { card: 5, count: 1 },
    { card: 4, count: 1 },
    { card: 3, count: 1 },
    { card: 2, count: 1 },
  ];


  const [currentCount, setCount] = useState(0);

  const onPressCard = () =>{
    setCount   1
  }

  return (
    <View style={styles.app}>
      <CardCount useState={currentCount}/>
      <View style={styles.cards} onPress={onPressCard()}>
      {cards.map((index) =>(<Card item={index} />))}
      </View>
    </View>
  );
}

The custom component I am using. This component is where the count changes.

export const CardCount = ({useState}) => {
  return (
    <Text style={styles.count}>{useState}</Text>
  )
}

How can I update the state using the object cards?

Thanks

CodePudding user response:

Even outside of React as a framework, or JavaScript as a language, this statement by itself does nothing:

setCount   1

Even if it produces a result, nothing is ever done with that result.

In this specific case, setCount is a function. You call a function and pass it arguments/parameters:

setCount(currentCount   1);

CodePudding user response:

You use it like you do in normal react.

export default function App() {

  const cards = [
    { card: "A", count: -1 },
    { card: "K", count: -1 },
    { card: "Q", count: -1 },
    { card: "J", count: -1 },
    { card: 10, count: -1 },
    { card: 9, count: 0 },
    { card: 8, count: 0 },
    { card: 7, count: 0 },
    { card: 6, count: 1 },
    { card: 5, count: 1 },
    { card: 4, count: 1 },
    { card: 3, count: 1 },
    { card: 2, count: 1 },
  ];


  const [count, setCount] = useState(0);

  const onPressCard = () =>{
    setCount((currentCount) => currentCount   1);
  }

  return (
    <View style={styles.app}>
      <CardCount count={count}/>
      <View style={styles.cards} onPress={onPressCard()}>
      {cards.map((index) =>(<Card item={index} />))}
      </View>
    </View>
  );
}
export const CardCount = ({count}) => {
  return (
    <Text style={styles.count}>{count}</Text>
  )
}
  • Related