0

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.

8
  • 1
    Where did you put the console.log? Commented Apr 13, 2021 at 13:46
  • 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. Commented Apr 13, 2021 at 13:51
  • Why do you declare a function(fetchInfo) inside the useEffect and then call it, but not directly execute the content of the fetchInfo function? Commented Apr 13, 2021 at 13:53
  • I have added complete code . Please have a look. Commented Apr 13, 2021 at 15:04
  • @SinanYaman Are you telling me to run the function, how I have tried in second attempt. Commented Apr 13, 2021 at 15:06

1 Answer 1

1

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>

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

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.