Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When cycling through options in a list the only items displayed is the last option (displayed twice) and the second to last option (react native JS)

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);
}

Console Log

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading