Rahul
Rahul

Reputation: 33

react shows error when submit button click

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

Upvotes: 0

Views: 67

Answers (4)

Abdullah Abid
Abdullah Abid

Reputation: 1661

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

Upvotes: 0

user11891640
user11891640

Reputation:

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

Upvotes: 0

Thanveer Shah
Thanveer Shah

Reputation: 3323

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

Upvotes: 2

Edgar Henriquez
Edgar Henriquez

Reputation: 1383

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.

Upvotes: 3

Related Questions