Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fetch api as soon as page is loaded in ReactJS?

Whenever i visit a page it should automatically fetch the api

import React from 'react'

const comp = () => {
fetch("api url").then((res)=>console.log(res))
  return (
    <div>comp</div>
  )
}

export default comp

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It is very simple using react hook use effect please learn basics of useffect hook on react docs or any youtube tutorial and as for the answer

import React, { useEffect } from 'react'

const comp = () => {
useEffect(() => {
    fetch("api url").then((res)=>console.log(res))
}, [])


  return (
    <div>comp</div>
  )
}

export default comp

here empty dependency means every time page loads only once

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading