0

I have an array of objects that I load from a json file and I want each item to load separately when I click a button. I completed that but the main problem is when the index goes out of bounds so then it shows

TypeError "Cannot read property 'content' of undefined".

How can I make then index be 0 again when the index reaches the last item? I tried solving it by including some if statements inside the button but no luck. Here is the related part of the code till now:

function App() {
  const classes = useStyles();
  const questions_size = Data.length;
  const [num, setNum] = useState(0);
  const current = Data[num].content;

  (...)
  return (
    <Container>
      <Typography variant="h3" gutterBottom>
        About
      </Typography>
      <Button variant="contained" color="primary" onClick={()=> num<questions_size?setNum(num+1): setNum(0)}>Επομενο</Button>
      <Card className={classes.root}>
        <CardContent>

          <Typography variant="body1" gutterBottom>
            <p style={{ fontFamily: 'Tangerine, serif', fontSize: '35px', textShadow: '4px 4px 4px #aaa'}}>{current}</p>
          </Typography>
        </CardContent>
      </Card>
    </Container>
  )
1
  • would you show the Data? Commented Jun 3, 2020 at 1:38

2 Answers 2

2

The issue with your current approach is that the highest valid index is questions_size - 1, it should work like this:

onClick={() => num < questions_size - 1 ? setNum(num + 1) : setNum(0)}

Another option is to use the remainder operator:

onClick={() => setNum(num + 1 % questions_size)}
Sign up to request clarification or add additional context in comments.

Comments

1

this code will only run when the data changes.

useEffect(() => {
  if (num > Data.length) {
    setNum(0)
  }
},[Data])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.