Reputation: 861
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.
Upvotes: 0
Views: 684
Reputation: 8329
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>
Upvotes: 1