0

I am new to React. I don't understand why it's showing an error. I need to repeat the array object but when It reaches the last array it does not restart.
https://codesandbox.io/s/generate-quote-xpu1q

index.js:

import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  rootElement
);

app.js:

import React, { useState, useEffect } from "react";
import "./styles.css";
// import { qutoes } from "./Fetch";

export default function App() {
  // const data = qutoes;
  const [data, setData] = useState("loading");
  const [index, setIndex] = useState(0);

  const qutoesBtn = () => {
    if (index === data.length - 1) {
      setIndex(0);
    } else {
      setIndex(index + 1);
    }
  };
  useEffect(() => {
    fetch("https://type.fit/api/quotes")
      .then(res => res.json())
      .then(res2 => {
        console.log(res2.slice(0, 10));
        const lists = res2.slice(0, 10);
        setData(lists);
      });
  }, []);
  return (
    <div className="App">
      <h1>Generate Quote</h1>
      <h4>
        {data === "loading" ? (
          "loading...!!"
        ) : (
          <div>
            My qutoes is ---- <br />
            <span> {data[index].text}</span> <br /> Author is --
            {data[index].author}
          </div>
        )}
      </h4>

      <button onClick={qutoesBtn}>Generate Quote</button>
    </div>
  );
}

enter image description here

4 Answers 4

3

You should change your condition to update once the index reaches data.length - 1

if (index === (data.length - 1)) {
  setIndex(0);
}

Remember that given an array [1, 2, 3] the length is 3, but the maximum index is 2 because arrays indexes start at 0, so when index is equal to the data.length React is going to try to access that position giving you the error that you're experiencing.

Sign up to request clarification or add additional context in comments.

Comments

2

It is because you are not checking if the array has reached the last item in the button click, So if you don't check it in the button click then it will increment the index again before it even gets to check , So change your code to this:

const qutoesBtn = () => {
    if (index === data.length - 1) {
      setIndex(0);
    } else {
      setIndex(index + 1);
    }
  };

Here -1 refers to the last item in the array

Comments

0

I think you need a condition where if the array reaches the end Then start it back at zero

Comments

0

You wanna Check if the next item exceeds the length and you want to check it inside the qutoesBtn

 const qutoesBtn = () => {
    setIndex(index + 1);
    if (index + 1 >= data.length) {
      setIndex(0);
    }

    console.log(index);
  };

CodeSandbox here

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.