Need help with React Hooks

so I have a button, in which I push should fetch the data. However, when I start the page, I see the button for about 2 secs and then the data appears, without even clicking. I know there is something wrong with my Hooks(useState and useEffect) . can some help me?

I dont want the data to appear until I have clicked the button… I dont know what is wrong.

import {useEffect, useState} from 'react';
import React from "react"
import './App.css';
import { fetchData } from './api.js'

function App() {

  const [books, setBooks] = useState();
  
  useEffect(()=>{fetchData().then(lemons => setBooks(lemons))},)

  return (
    <div className="App">
      <h1>Game of Thrones Books</h1>
      <h2>Fetch a list from an API and display it</h2>

      {/* Fetch data from API */}
      <div>
        <button className="fetch-button" onClick={fetchData}>
          Fetch Data
        </button>
        <br />
      </div>

      {/* Display data from API */}
      <div className="books">
        {books &&
          books.map((book, index) => {
            const cleanedDate = new Date(book.released).toDateString();
            const authors = book.authors.join(', ');

            return (
              <div className="book" key={index}>
                <h3>Book {index + 1}</h3>
                <h2>{book.name}</h2>

                <div className="details">
                  <p>👨: {authors}</p>
                  <p>📖: {book.numberOfPages} pages</p>
                  <p>🏘️: {book.country}</p>
                  <p>⏰: {cleanedDate}</p>
                </div>
              </div>
            );
          })}
      </div>
    </div>
  );
}
 export default App

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

1 Like

What value do you think books is after the above line executes?

What do you think setBooks does here?

What you’re trying there, that isn’t how useEffect works. When the component mounts, the effect fires once, and then if you provide an array of values it depends on, it will fire every time one of those changes. The hook attempts to keep component state (its dependencies, the values in the array) in sync.

Executing fetchData when you click the button isn’t going to do anything useful; you’ve already executed in in useEffect.

What you normally do is provide some value – for example a url string – and set that as state, starting as (eg) an empty string. That state is a dependency of useEffect. Then when that string changes, if it isn’t empty, fire the function, get and set the data

thank you, I see what I was doing wrong…