Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Difference Between AJAX And Fetch API
Next article icon

ReactJS AJAX and API

Last Updated : 30 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

APIs are used for fetching data from the server and using AJAX and API we call data asynchronously and show it in our HTML. You can make API requests by using browser built-in fetch function or third party libraries like Axios.

Prerequisites:

  • JavaScript and JSX
  • Knowledge about react state and setState
  • Knowledge about React Components and how to make them
  • React Life cycle methods

AJAX Calls in React

AJAX or Asynchronous JavaScript and XML is used to make asynchronous requests to the servers. Ajax in React is mainly used to fetch and send the data to APIs enabling the dynamic data loading and UI updates.

  • For class-based components, AJAX calls should be made within the componentDidMount() lifecycle method. This ensures that the component has mounted and is ready to handle data updates by setting the component’s state with the data retrieved from the server.
  • In functional components, AJAX calls are typically made inside the useEffect() hook, which can mimic the behavior of componentDidMount() by running only once after the initial render if an empty dependency array ([]) is passed.

Below code example of how to use API:

Example 1: In this example, React class component fetches data from an API using fetch() in componentDidMount(), manages loading and error states, and renders the fetched data as a list once the API request completes.

JavaScript
// Filename - App.js  class MyComponent extends React.Component { 	constructor(props) { 		super(props); 		this.state = { 			error: null, 			dataFetched: false, 			data: [] 		}; 	}  	componentDidMount() { 		fetch("https://api.toptensongs.com/data") 			.then((res) => res.json()) 			.then( 				(response) => { 					this.setState({ 						dataFetched: true, 						data: response.data 					}); 				}, 				(error) => { 					this.setState({ 						dataFetched: true, 						error 					}); 				} 			); 	}  	render() { 		const { error, dataFetched, data } = this.state; 		if (error) { 			return <div>Error: {error.message}</div>; 		} else if (!isLoaded) { 			return <div>Loading...</div>; 		} else { 			return ( 				<ol> 					{data.map((value) => ( 						<li key={value.name}> 							{value.name} - {item.artist} 						</li> 					))} 				</ol> 			); 		} 	} } 

So, this is a simple example in which we explained how to use API, so it is important to note that error handling is really important because if the data is not fetched it should show an error. But here is another example if we want to load data on some actions like on click like fetching someplace’s weather then we can’t use componentDidMount() because it is only called once so for that we can use componentWillUpdate() but it was removed so, we can use a function also in place of componentWillUpdate() and make API request in a function.

Example 2: This example demonstrates fetching weather data from the OpenWeather API using AJAX in the getWeather method. It captures user input for location, sends an API request, and displays the location, temperature, and weather condition dynamically.

JavaScript
// Filename - App.js  class Weather extends React.Component { 	constructor(props) { 		super(props);  		this.state = { 			location: "", 			place: "", 			temp: "", 			weather: "" 		}; 	}  	render() { 		return ( 			<div className="weather"> 				<label htmlFor="text">Enter Location</label> 				<br /> 				<div id="location"> 					<input 						onChange={this.changeValue} 						type="text" 						value={this.state.location} 					/> 				</div> 				<div className="button"> 					<button onClick={this.getWeather}>Check Weather</button> 				</div> 				<div> 					<h1>Location: {this.state.place}</h1> 					<h3>Temperature: {this.state.temp} C</h3> 					<h3>Condition: {this.state.weather}</h3> 				</div> 			</div> 		); 	}  	changeValue = (event) => { 		this.setState({ 			location: event.target.value 		}); 	};  	getWeather = () => { 		fetch(` https://api.openweathermap.org/data/2.5/weather?q=${this.state.location}&units=metric&APPID=APIKEY`) 			.then((response) => response.json()) 			.then((data) => { 				this.setState({ 					place: data.name, 					temp: data.main.temp, 					weather: data.weather[0].main 				}); 			}); 	}; }  export default class Main extends React.Component { 	constructor(props) { 		super(props);  		this.state = {}; 	}  	render() { 		return ( 			<div className="main"> 				<div className="title">What's the Weather?</div> 				<hr /> 				<Weather /> 			</div> 		); 	} } 

Output: So, what we did here we just moved the API request in getWeather() function and so it will only be called whenever we will make click on check weather.



Next Article
Difference Between AJAX And Fetch API

I

iamsahil1910
Improve
Article Tags :
  • ReactJS
  • Web Technologies

Similar Reads

  • Axios in React Native
    Axios is a widely used HTTP client for making REST API calls. You can use this in React Native to get data from any REST API. Axios in React NativeAxios is a library that helps you send HTTP requests in React Native apps. It allows mobile devices to communicate with a server, enabling them to send a
    8 min read
  • Is ReactJS a Framework?
    When it comes to building modern web applications, ReactJS has become one of the most popular tools in the developer’s toolkit. But there is often confusion about whether ReactJS is a framework or a library. Understanding this distinction can help you make more informed decisions about using ReactJS
    4 min read
  • ReactJS Examples
    This article contains a wide collection of React JS examples. These examples are categorized based on the topics, including components, props, hooks, and advanced topics in React. Many of these program examples contain multiple approaches to solve the respective problems. These React JS examples pro
    5 min read
  • Difference Between AJAX And Fetch API
    AJAX (Asynchronous JavaScript and XML) and Fetch API are both powerful tools used in modern web development for making asynchronous HTTP requests. Each has its strengths and specific use cases that developers should consider when deciding which to use. In this article, we will see the main differenc
    5 min read
  • Explain JSON in AJAX
    AJAX is a very popular concept that is used to update the page without reloading the page. AJAX stands for Asynchronous Javascript And XML and because of that many Developers think that AJAX will only use XML to export and import data but that is not true. AJAX can use XML to transport any kind of d
    5 min read
  • Difference Between JSON and AJAX
    AJAXAjax is an acronym for Asynchronous Javascript and XML. It is used to communicate with the server without refreshing the web page and thus increasing the user experience and better performance. There are two types of requests synchronous as well as asynchronous. Synchronous requests are the one
    5 min read
  • What is polling in AJAX ?
    In this article, we will see the polling with AJAX. Here, we are trying to create a polling-like experience using Javascript features like AJAX and Fetch API. Polling is the process of constantly and successively making HTTP calls until a required response is received. It is a very basic method to c
    4 min read
  • What is Ajax ?
    Imagine browsing a website and being able to submit a form, load new content, or update information without having to refresh the entire page. That's the magic of AJAX. Asynchronous JavaScript and XML (AJAX) is a web development technique that allows web pages to communicate with a web server asynch
    5 min read
  • ReactJS CORS Options
    In ReactJS, Cross-Origin Resource Sharing or CORS requests refers to the method that allows you to make requests to the server deployed at a different domain. As a reference, if the frontend and backend are at two different domains, we need CORS there. Handling Cross-Origin Resource Sharing (CORS) i
    3 min read
  • IP address finder app using ReactJS
    In this article, we will be building an IP address finder app that lets you find your client's approximate location on a map. An IP address is a unique address that identifies a device on the internet or a local network. IP stands for "Internet Protocol," which is the set of rules governing the form
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences