Can we pass an asynchronous function (example fetchData() ) in a dependancy array of useEffect of a react component ? example :
useEffect(()=>{fetchData().then(data=>{ //do something with data like setting state
)}},[fetchData])
CodePudding user response:
Yes this is fine. Just be aware that a new, potentially overlapping, request will be made every time fetchData changes. If you only want to make this request once use an empty dependency array.
CodePudding user response:
yes for sure but you need to pass empty dependency to avoid overlapping or pass an state array dependency:
useEffect(() => {
async function fetchMyAPI() {
let response = await fetch('api/data')
response = await response.json()
dataSet(response)
}
fetchMyAPI()
}, [])
