Education
Developer Advocate
Last updated on Sep 5, 2024
Last updated on Sep 4, 2023
React, a JavaScript library for building user interfaces provides a top-level API that contains the React component model. This model allows developers to build encapsulated components that manage their own state, and then compose them to make complex user interfaces. In this blog, we'll delve into the React top-level API, React components, and how to make API calls in React.
The React top level API is the set of React functions and properties that are available globally. It's the entry point to the React library. When you write import React from 'react';, you're accessing the React top level API. This API includes methods for creating React elements, components, and more.
1 import React from 'react'; 2
A React component is a self-contained piece of code that outputs a React element to be rendered to the page. The output can be a single element or multiple elements that make up a part of the user interface.
React components can be defined using ES6 classes or functions. Here's an example of a class component:
1 class Greeting extends React.Component { 2 render() { 3 return <h1>Hello, {this.props.name}</h1>; 4 } 5 } 6 7 export default Greeting; 8
In the above example, class Greeting extends React.Component is creating a new React component. The render method is a part of the React component's render API. It returns a React element which represents the component's UI.
React components can also be stateless, meaning they simply take in props and return a React element. Here's an example of a stateless component:
1 function Greeting(props) { 2 return <h1>Hello, {props.name}</h1>; 3 } 4 5 export default Greeting; 6
React itself doesn't have a built-in method to make HTTP requests or fetch data from APIs. However, it works seamlessly with various HTTP request libraries such as Fetch API, Axios, and others. In this section, we'll explore how to make API calls using the Fetch API.
The Fetch API provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
Here's an example of a basic fetch request:
1 fetch('https://api.example.com/data') 2 .then(response => response.json()) 3 .then(data => console.log(data)) 4 .catch((error) => { 5 console.error('Error:', error); 6 }); 7
In the above example, fetch('https://api.example.com/data') is making an API call to the specified API endpoint. The then() method is used to handle the response data. The response.json() method reads the response and returns the data in JSON format.
As we continue to delve into the intricacies of React and API integrations, it's impossible to ignore the transformative impact of artificial intelligence (AI) in the realm of software development. One such innovation that has caught the attention of many React developers is WiseGPT.
WiseGPT is a promptless generative AI designed specifically for developers. It's like having a pair of extra hands that write code in your style, without any context limit. It's not just about writing code, WiseGPT also provides API integration by accepting Postman collections, making it a powerful tool for developers working with APIs.
What's even more fascinating is that WiseGPT supports extending UI in the VSCode itself. This means you will be able to leverage the power of AI right within your favorite code editor, making your development process smoother and more efficient.
The beauty of WiseGPT lies in its ability to seamlessly blend into your workflow, enhancing your capabilities without disrupting your established routines. It's not about replacing developers, but rather augmenting their skills and freeing them from repetitive tasks to focus on more complex and creative aspects of development.
As we continue to explore the world of React and API calls, it's exciting to think about how tools like WiseGPT can shape our future as developers. The intersection of AI and coding opens up a world of possibilities that we're just beginning to explore. So, as you delve deeper into your React journey, remember to keep an open mind and embrace the potential that AI brings to the table. Happy coding!
Typically, API calls are made in the lifecycle method componentDidMount() for class components or the useEffect() hook for functional components. This is because we want to fetch the data right after the component has been inserted into the DOM.
Here's an example of a class component making an API call:
1 class MyComponent extends React.Component { 2 constructor(props) { 3 super(props); 4 this.state = { 5 data: [], 6 }; 7 } 8 9 componentDidMount() { 10 fetch('https://api.example.com/data') 11 .then(response => response.json()) 12 .then(data => this.setState({ data: data })); 13 } 14 15 render() { 16 return ( 17 <div> 18 {this.state.data.map(item => ( 19 <p key={item.id}>{item.name}</p> 20 ))} 21 </div> 22 ); 23 } 24 } 25 26 export default MyComponent; 27
In the above example, class MyComponent extends React.Component is creating a new React component. The componentDidMount() method is making an API call and updating the component's state with the response data. The render() method is then rendering the data to the DOM.
When making API calls, the response data is typically in JSON format. This data can be complex, containing deep data structures. React provides various ways to handle and display this data.
In the above example, the response data is an array of items. Each item is an object with properties id and name. The render()
method is mapping over the array and rendering a paragraph element for each item.
React components can have state. State is a JavaScript object that stores component's local data. It can be changed over time, typically as a result of user actions or API calls.
In the above example, the component's state is initialized with an empty array data. When the API call is made and the response data is received, the state is updated with the new data using this.setState({ data: data })
.
React's state and lifecycle methods provide a powerful way to fetch data, handle response data, and update the UI based on the data.
In the third and final part of this blog, we'll explore more complex topics such as error handling, loading states, and more. We'll also discuss how to use other libraries like Axios for making API calls. Stay tuned!
When making API calls, it's important to handle potential errors. This could be network errors, server errors, or even parsing errors when trying to convert the response data.
Here's an example of error handling in a fetch request:
1 fetch('https://api.example.com/data') 2 .then(response => { 3 if (!response.ok) { 4 throw new Error('Network response was not ok'); 5 } 6 return response.json(); 7 }) 8 .then(data => console.log(data)) 9 .catch(error => console.error('Error:', error)); 10
In the above example, if the fetch request does not return an OK response, an error is thrown. This error is then caught in the catch() method and logged to the console.
When making an API call, there might be a delay while waiting for the response. It's a good practice to show a loading indicator during this time.
Here's an example of managing a loading state:
1 class MyComponent extends React.Component { 2 constructor(props) { 3 super(props); 4 this.state = { 5 data: [], 6 isLoading: true, 7 }; 8 } 9 10 componentDidMount() { 11 fetch('https://api.example.com/data') 12 .then(response => response.json()) 13 .then(data => this.setState({ data: data, isLoading: false })); 14 } 15 16 render() { 17 if (this.state.isLoading) { 18 return <div>Loading...</div>; 19 } 20 21 return ( 22 <div> 23 {this.state.data.map(item => ( 24 <p key={item.id}>{item.name}</p> 25 ))} 26 </div> 27 ); 28 } 29 } 30 31 export default MyComponent; 32
In the above example, the isLoading state is initially set to true. When the API call is made and the response data is received, isLoading is set to false. The render() method then checks isLoading and renders either a loading indicator or the data.
Axios is a popular, promise-based HTTP client that works in both the browser and Node.js environments. It provides a simple and clean API for making HTTP requests.
Here's an example of making an API call with Axios:
1 import axios from 'axios'; 2 3 axios.get('https://api.example.com/data') 4 .then(response => { 5 console.log(response.data); 6 }) 7 .catch(error => { 8 console.error('Error:', error); 9 }); 10
In the above example, axios.get('https://api.example.com/data')
is making an API call. The then() method is used to handle the response data, and the catch() method is used to handle any errors.
In this three-part blog series, we've taken a deep dive into the React top level API, React components, and the process of making API calls in React. We've explored how to handle response data, manage state based on API responses, handle errors, manage loading states, and even how to use other libraries like Axios for making API calls.
Understanding these concepts is crucial for any developer working with React. The ability to fetch data from an API, handle the response, and update the UI accordingly is a common requirement in modern web applications. React's top level API and component model provide a powerful and flexible way to build such applications.
Whether you're a beginner just starting out with React, or a seasoned developer looking to deepen your understanding, we hope this series has provided valuable insights and practical examples to help you on your journey. Remember, the key to mastering these concepts is practice. So, roll up your sleeves, start coding, and don't be afraid to experiment and learn from your mistakes.
Happy coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.