0
votes

I have been working with react-hooks for a while now, and was under impression useEffect is called once there is some changes been made. But in my case when calling api in useEffect, it renders data continuously.

Here is my useEffect code:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

export default function BookFunction() {
    
    const [bookData, setBookData] = useState([])

     useEffect(() => {
         function fetchInfo() {
            axios.post(`/api/book/bookDetails`).then((data) => {
                setBookData(data.data)
                }).catch(error => {
                    console.log(error);
                })
         }
         fetchInfo()
     }, [])

    console.log('this is bookdata',bookData) => bookdata is printed in the browser again and again

} 

when I do console.log(bookData), it renders over and over again in browser.

How can I prevent this, such that it renders only once or twice?

I tried doing without using useEffect as,

     function fetchInfo() {
        axios.post(`/api/book/bookDetails`).then((data) => {
            setBookData(data.data)
            }).catch(error => {
                console.log(error);
            })
     }
     fetchInfo()

But it crashed the system.

Is there anyother way such that I can achieve my goal? If anyone needs any further information please let me know.

1
Where did you put the console.log?Nimna Perera
By the look of your code, useEffect should run only once, on mount. However, it's important to know where exactly have you put the console.log.Plabon Dutta
Why do you declare a function(fetchInfo) inside the useEffect and then call it, but not directly execute the content of the fetchInfo function?Sinan Yaman
I have added complete code . Please have a look.Siva Pradhan
@SinanYaman Are you telling me to run the function, how I have tried in second attempt.Siva Pradhan

1 Answers

1
votes

Recreated your use case with a dummy API, I don't see this problem with fetch. The difference is that I used a function in setBookData.

const { useEffect, useState } = React

const App = () => {
  const [bookData, setBookData] = useState([])
  
  useEffect(() => {
    function fetchInfo() {
      fetch('https://jsonplaceholder.typicode.com/todos')
        .then(response => response.json())
        .then(arr => {
          setBookData(() => {
            return arr.map(({title}) => title)
          })
        })
    }
    fetchInfo()
  }, [])

  console.log('this is bookdata', bookData)

  return (
    <div>
      {
        bookData.map((book, i) => {
          return `${i + 1}. ${book}`
        })
      }
    </div>
  )
}


ReactDOM.render(<App />, document.querySelector("#app"))
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

<div id="app"></div>