Home > Software engineering >  How to avoid returning undefined if condition is not met
How to avoid returning undefined if condition is not met

Time:11-22

I am building a react app and I have an array of objects (items) that I would like to loop over and display the various objects based on an index. I set the index using useState and a button that the user clicks.

    const [index, setIndex] = useState(0);
    const itemsLength = items.length;

    const nextBtn = () => {
    if(index <= itemsLength) {
        setIndex(index   1);
    } else {
        setIndex(0)
    }
   }

When I console.log the index it starts at 0 and gets to 3 just fine, but after reaching the itemsLength where it should setIndex to 0, it returns undefined and I have to click on the button 3 times before it gets back to 0.

How can I get it to get back to 0 without returning undefined.

I am new to javascript and have been at this for hours. Please help.

CodePudding user response:

Its because array is zero indexed, and you're counting from zero it means ten elements is from 0 to 9 and not 10 exactly so be careful on using <= and check if just < will work for you.

Look below example where mine loops just fine

const { useState } = React;

function Example() {

  const [index, setIndex] = useState(0);
  const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 19];

  const nextBtn = () => {
    setIndex((prev) => {
      if (prev < items.length) {
        return prev   1;
      } else {
        return 0;
      }
    });
  };

  return (
    <div className="App">
      <button onClick={nextBtn}>
        next {index}
      </button>
    </div>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Your function must be like this:

const nextBtn = () => {
    if (index < itemsLength - 1) {
      setIndex(index   1);
    } else {
      setIndex(0);
    }
  };
  • Related