I am trying to update the using useState in react native but not working properly for last and first value

Viewed 146
import React, { useState } from 'react';
import { View, Pressable,Text } from 'react-native';
export default function App(){
  const [count, setcount] = useState([2,5,4,1,8])
  const [b, setb] = useState(0)
  return (
    <View>
    <Pressable onPress ={ () => setb(b+1)}>+</Pressable>//Updating value and showing from array
    <Text> {count[b]} </Text>
    <Pressable onPress ={ () => setb(b-1) }>-</Pressable>//Same for decrements
    </View>
  )
}

The code doesn't work properly for the first and last value means it is going to index -1 and also out of bound at the last index. Please highlight where I am doing wrong.

1 Answers

Use functional state updates to increment/decrement the b state and add logic to keep the b value "in bounds".

export default function App(){
  const [count, setcount] = useState([2,5,4,1,8])
  const [b, setb] = useState(0)
  return (
    <View>
      <Pressable onPress ={() => setb(b => Math.min(b + 1, count.length - 1))}>
        +
      </Pressable>
      <Text>{count[b]}</Text>
      <Pressable onPress ={() => setb(b => Math.max(b - 1, 0))}>
        -
      </Pressable>
    </View>
  );
}

Edit i-am-trying-to-update-the-using-usestate-in-react-native-but-not-working-properl

Related