I am trying to cycle through options in a list using left and right buttons that call the functions cycleLeft()
and cycleRight()
, but instead all I get is the second to last option displayed twice in a row and then the last option displayed once.
this is for a react native app inside the main app function. any help is appreciated.
var gamesList = ["Quadratic", "Magic Square", "Settings", "Option 3"];
var index = 0;
var game = gamesList[index];
const [gameText, setGameText] = useState(gamesList[index]);
const [gameGame, setGameGame] = useState(gamesList[index]);
const zAnim = useRef(new Animated.ValueXY({ x: 0, y: 1000 })).current;
const cycleLeft = () => {
index = index - 1;
if (index < 0) { index = gamesList.length - 1; };
game = gamesList[index];
setGameText(gamesList[index]);
console.log(game " " index);
}
const cycleRight = () => {
index = index 1;
if (index > gamesList.length - 1) { index = 0; };
game = gamesList[index];
setGameText(gamesList[index]);
console.log(game " " index);
}
CodePudding user response:
index
should be stateful instead of gameText
var gamesList = ["Quadratic", "Magic Square", "Settings", "Option 3"];
const [index, setIndex] = useState(0);
const cycleLeft = () => {
setIndex(prevIndex => prevIndex - 1 < 0 ? gamesList.length - 1 : prevIndex - 1);
}
const cycleRight = () => {
setIndex(prevIndex => prevIndex 1 > gamesList.length - 1 ? 0 : prevIndex 1);
}
//just for logging
useEffect(() => {
console.log(gamesList[index] " " index);
}, [index]);
Wherever you were using gameText
, you can just use gamesList[index]
instead.