ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Thursday, December 1, 2022

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

 December 01, 2022     javascript, reactjs   

Issue

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

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



Answered By - Shubham Yadav
Answer Checked By - - Mary Flores (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix