Home > OS >  How can I update an array using useState, with as many numbers as the ones I pass to the function?
How can I update an array using useState, with as many numbers as the ones I pass to the function?

Time:02-12

I am trying to make an image slider that gives you n new images every time you click. I am struggling to understand how to make this piece of code dynamic so that it updates the array that takes care of the indexes as many times as the number I pass to the function (in this case 3)

  const handleIncrement = () => {
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1]   1,
      prevIndex[prevIndex.length - 1]   2,
      prevIndex[prevIndex.length - 1]   3,
    ]);
  };

This is the entire code

function useImageSlider(range: number = 3, length: number, steps: number = 1) {
  const [index, setIndex] = useState<number[]>(Array.from(Array(range).keys()));

  const handleDecrement = () => {
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1] - 1,
      prevIndex[prevIndex.length - 1] - 2,
      prevIndex[prevIndex.length - 1] - 3,
    ]);
  };
  const handleIncrement = () => {
    index[index.length - 1]   steps   1 >= length &&
      setIndex((prevState) => [...prevState, -1]);
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1]   1,
      prevIndex[prevIndex.length - 1]   2,
      prevIndex[prevIndex.length - 1]   3,
    ]);
  };
  return { length, steps, handleIncrement, handleDecrement, index };
}
export default useImageSlider;

CodePudding user response:

const handleIncrement = (range) => {
setIndex((prevIndex) => [...Array(range).keys()].map(arrIndex =>
  prevIndex[prevIndex.length - 1]   arrIndex   1));
};
  • Related