Exploring the Best Full-Stack Development Frameworks in 2023

In today’s ever-evolving digital landscape, full-stack web development has emerged as a powerful approach to creating dynamic and feature-rich web application.

This comprehensive development method combines both back-end and front-end development, providing developers with the tools they need to build sophisticated and interactive web apps.

With the rising demand for seamless user experiences and cross-platform compatibility, full-stack development frameworks have become increasingly popular, allowing developers to efficiently create robust web applications.

Let’s dive into the top full-stack development frameworks that are shaping the web development landscape in 2023.

Top 5 Benefits of Using Web Development Frameworks

Web development frameworks are essential tools for developers that simplify the creation of web applications by providing pre-built components and functionalities.

Here are five benefits of using web development frameworks:

  1. Streamlined Development:
    Frameworks offer ready-to-use components, templates, and libraries, reducing development time and effort significantly.
  2. Enhanced Productivity:
    By adhering to best practices and standard coding conventions, frameworks enable developers to work more efficiently and produce high-quality code.
  3. Improved Code Quality:
    Frameworks promote modularity and code reusability, resulting in well-structured and maintainable codebases.
  4. Cross-Platform Compatibility:
    Many frameworks support multi-platform development, allowing web apps to reach a broader audience across various devices.
  5. Community Support:
    Popular frameworks have large and active communities, providing developers with resources, updates, and support.

Here are five key differences between front-end and back-end frameworks:

Development Focus

  • Front-End Frameworks:
    Focus on user interface (UI) and user experience (UX) design, handling the presentation layer visible to users.
  • Back-End Frameworks:
    Deal with the server-side operations, managing databases, authentication, and business logic.

Languages:

  • Front-End Frameworks:
    Primarily use HTML, CSS, and JavaScript for creating interactive user interfaces.
  • Back-End Frameworks:
    Employ various programming languages such as Python, PHP, Ruby, and JavaScript (Node.js) to handle server operations.

Responsibilities:

  • Front-End Frameworks:
    Handle client-side tasks like UI rendering, user input validation, and DOM manipulation.
  • Back-End Frameworks:
    Manage server-side tasks like database interactions, business logic, and server security.

User Interaction:

  • Front-End Frameworks:
    Focus on enabling user interactions and experiences, aiming to deliver a seamless UI/UX.
  • Back-End Frameworks:
    Concentrate on processing user inputs, executing requests, and managing server operations.

Presentation vs. Functionality:

  • Front-End Frameworks:
    Emphasize the presentation and look of the web application, ensuring a visually appealing design.
  • Back-End Frameworks:
    Concentrate on the functionality and performance of the web application, ensuring efficient data processing and handling.

All Types of Web Framework Architectures:

Web development frameworks follow various architectures or design patterns to organize and structure applications. Let’s explore three common architecture types:

Model-View-Controller (MVC):

MVC is a widely-used architecture in web development, dividing the application into three interconnected components.

Benefits:

  • Separation of Concerns:
    MVC separates the application into distinct parts, allowing developers to work on specific components independently.
  • Reusability:
    Models and Views can be reused in different parts of the application, promoting code reusability.
  • Maintainability:
    MVC architecture eases the maintenance process as developers can update individual components without affecting others.

Model View-View-Model (MVVM):

MVVM is a variant of the MVC pattern, commonly used in front-end development for creating dynamic user interfaces.

Benefits:

  • Two-Way Data Binding:
    MVVM enables automatic synchronization between the model and the view, simplifying data handling.
  • Separation of UI and Logic:
    MVVM separates the UI and application logic, enhancing code maintainability and readability.
  • Testability:
    MVVM architecture facilitates unit testing, as the UI logic is separated from the business logic.

Three-Tier Architecture:

The three-tier architecture divides the application into three layers: presentation/UI, application logic/functionality, and the database.

Benefits:

  • Scalability:
    Three-tier architecture enables each layer to be independently scaled, enhancing overall application scalability.
  • Modularity:
    Separation of concerns makes the application modular and easy to maintain.
  • Resilience:
    Isolating layers enhances the application’s resilience, allowing one layer to be updated without affecting the others.

Top 10 Statistics and Facts from Various Sources:

  • Full-stack web development is projected to be one of the most sought-after tech skills, with an expected growth rate of over 20% annually.
  • ReactJS remains the most popular front-end framework, with over 60% of developers choosing it for web app development.
  • Angular is widely used in enterprise-level applications, with over 40% of Fortune 500 companies employing it.
  • Django, a Python-based back-end framework, has experienced a 30% increase in active projects over the past year.
  • Laravel’s community has grown significantly, surpassing three million developers worldwide.
  • NodeJS, known for its speed and scalability, is utilized by major companies such as Netflix and LinkedIn.
  • Ruby on Rails remains a popular choice among startups and small businesses due to its rapid development capabilities.
  • Flask, a lightweight Python framework, has witnessed increased adoption for its simplicity and flexibility.
  • CodeIgniter continues to be favored by developers seeking a lightweight PHP framework with minimal setup requirements.
  • VueJS is experiencing significant growth in adoption, with over 40% increase in the number of projects compared to the previous year.

Top 10 Most Popular Web Frameworks of 2023:

  1. ReactJS
  2. Angular
  3. VueJS
  4. JQuery
  5. Django
  6. Flask
  7. Laravel
  8. CodeIgniter
  9. NodeJS
  10. Ruby-on-Rails

ReactJS:

ReactJS, developed by Facebook, was initially released in 2013. It was created to address the challenges of managing complex user interfaces in large-scale applications.

Never miss an update from us. Join 10,000+ marketers and leaders.

ReactJS has gained immense popularity among developers due to its simplicity, reusability of components, and performance optimization.

Its large and active community continuously contributes to its growth and offers a wide range of resources, making ReactJS the top choice for front-end development.

Benefits of ReactJS App Development:

  • Efficient Rendering:
    React’s virtual DOM efficiently updates only the necessary components, enhancing performance.
  • Component Reusability:
    React’s modular components facilitate code reusability, leading to faster web app development.
  • Strong Community Support:
    React app development has a vast and active community, providing continuous updates and support.
  • Seamless Integration with React Native:
    React Developers can easily reuse React components to build cross-platform mobile apps.
  • Virtual DOM:
    React’s virtual DOM improves performance by minimizing unnecessary updates.

Angular:

Angular, developed by Google, was first released in 2010 as AngularJS and later revamped as Angular in 2016. It was designed to create dynamic web applications with a focus on data binding and dependency injection.

Angular’s strong emphasis on code organization and maintainability has made it a popular choice for enterprise-level projects.

Angular’s robust features, two-way data binding, and seamless integration with TypeScript have earned it a strong following among developers.

Its scalability, extensive documentation, and active community support have solidified Angular’s position as a leading front-end framework.

Benefits of Angular App Development:

  • Two-Way Data Binding:
    Angular app development facilitates two-way data binding and simplifies data synchronization between the model and the view.
  • Dependency Injection:
    Its ‘dependency injection’ system facilitates code organization and testability.
  • Robust Testing Support:
    Its built-in testing tools allow Angular developers to create reliable and maintainable tests.
  • Modular Architecture:
    Angular’s modular approach promotes code maintainability and scalability.
  • Extensive Documentation:
    The development technology offers comprehensive documentation and resources, easing the learning process.

VueJS:

VueJS, created by Evan You and released in 2014, aimed to bridge the gap between React and Angular.

It was developed with a focus on simplicity, performance, and ease of integration.

Vue’s progressive nature allows developers to adopt it incrementally into existing projects.

VueJS’s intuitive syntax, reactive data binding, and seamless integration with other projects have contributed to its rising popularity among developers.

Its small file size, ease of learning, and ability to handle both small and large-scale applications make VueJS a preferred choice for developers worldwide.

Benefits of VueJS App Development:

  • Reactive Data Binding:
    Vue’s reactive data binding system ensures automatic UI updates with data changes.
  • Component-Based Architecture:
    The component-based approach enables VueJS developers to enhance code organization and reusability.
  • Lightweight Size:
    Its small file size ensures faster loading times and better overall performance.
  • Smooth Learning Curve:
    Its intuitive syntax makes it easy for developers to get started quickly.
  • Excellent Performance:
    The virtual DOM allows for efficient rendering and optimal application performance.

JQuery:

JQuery, developed by John Resig and released in 2006, was created to simplify DOM manipulation and event handling in JavaScript.

It revolutionized web development by providing a concise and cross-browser-compatible way to interact with HTML elements.

jQuery’s widespread adoption in the early days of web development cemented its popularity among developers.

Although newer frameworks have emerged, jQuery remains relevant for its simplicity, extensive plugin ecosystem, and compatibility with various browsers.

Benefits of JQuery App Development:

  • Simplified DOM Manipulation:
    JQuery’s concise syntax simplifies DOM manipulation and event handling.
  • Cross-Browser Compatibility:
    It ensures consistent behavior across different web browsers.
  • Extensive Plugin Ecosystem:
    The development technology has a vast plugin library that provides solutions for various web development needs.
  • Efficient Event Handling:
    Its event handling system allows JQuery developers to build smoother and more interactive user experiences.
  • Lightweight and Fast:
    Its small file size ensures quick loading times and reduced page load times.

Django:

Django, released in 2005, was created by a group of developers at the Lawrence Journal-World newspaper to build robust web applications rapidly.

It is written in Python and follows the “batteries included” philosophy, providing a wide range of built-in tools and features.

Django’s high-level abstractions, built-in admin interface, and efficient ORM have made it a preferred choice for web developers, particularly in the Python community.

Its scalability, security features, and active community support have solidified its reputation as a reliable back-end framework.

Benefits Django App Development:

  • High-Level Abstractions:
    Django web app development provides high-level abstractions, simplifying common web development tasks.
  • Built-In Admin Interface:
    The framework has built-in admin interface which facilitates Django developers to accelerate back-end development and content management.
  • Robust ORM:
    It features Object-Relational Mapping (ORM) streamlines database interactions and ensures data consistency.
  • Comprehensive Documentation:
    Django offers extensive documentation and resources, making it beginner-friendly.
  • Strong Community Support:
    The framework has an active community which ensures continuous improvement and troubleshooting.

Flask:

Flask, created by Armin Ronacher and released in 2010, was designed as a lightweight and flexible alternative to more extensive frameworks like Django.

It follows a minimalistic approach and allows developers to customize components based on project needs.

Flask’s minimal setup requirements, easy configuration, and extensibility have attracted developers looking for a flexible back-end framework.

Its small file size, straightforward learning curve, and compatibility with various Python libraries make it a popular choice for smaller to medium-sized projects.

Benefits of Flask App Development

  • Minimal Setup:
    Flask’s minimalistic design requires less setup and configuration, saving development time.
  • Easy-to-Extend Architecture:
    It allows developers to customize components based on specific project needs.
  • Customizable Components:
    The framework’s modular approach enables developers to use only the components they require.
  • Extensive Ecosystem:
    It benefits from a large library of extensions, facilitating additional functionalities.
  • Extensive Libraries:
    It has a vast range of libraries and supports various web development requirements.

Laravel:

Laravel, released in 2011 by Taylor Otwell, was built to provide an expressive and elegant syntax for PHP web development.

It follows the MVC pattern and includes the powerful Blade template engine, which simplifies front-end development.

Laravel’s expressive syntax, extensive library of packages, and active community have contributed to its rapid growth in popularity.

Its robust security features, built-in testing support, and seamless database migration tools make Laravel a top choice for PHP developers worldwide.

Benefits of Laravel App Development:

  • Blade Template Engine:
    Laravel’s Blade template engine simplifies and enhances front-end development.
  • ORM (Eloquent):
    Its Object-Relational Mapping (ORM) provides an elegant and expressive database query system.
  • Artisan Command-Line Tool:
    The framework has a built-in command-line tool which streamlines repetitive tasks and code generation.
  • Strong Security Features:
    Laravel incorporates robust security features to protect against common vulnerabilities.
  • Expressive Syntax:
    It has a clear and expressive syntax that makes code more readable and maintainable.

CodeIgniter:

CodeIgniter, initially released in 2006, was developed by EllisLab as a lightweight and high-performance PHP framework. It was created to offer a straightforward and efficient solution for building web applications without the restrictions of a full-fledged framework.

CodeIgniter’s minimal footprint, easy installation, and efficient performance have made it popular among developers looking for a lightweight PHP framework.

Its simple configuration and small learning curve make it an attractive option for small to medium-sized projects.

Benefits of CodeIgniter App Development:

  • Light Installation:
    CodeIgniter’s lightweight design ensures quick installation and reduced setup complexity.
  • Clear Documentation:
    It offers comprehensive and easy-to-follow documentation for developers.
  • Excellent Performance:
    The framework has an efficient architecture which guarantees fast-loading web applications.
  • Minimal Server Requirements:
    The development technology’s low server requirements make it compatible with various hosting environments.
  • Straightforward Configuration:
    CodeIgniter features an easy configuration process that speeds up project development.

NodeJS:

NodeJS, released in 2009 by Ryan Dahl, introduced server-side JavaScript execution using the V8 JavaScript engine.

It enables developers to build scalable and real-time applications by leveraging non-blocking I/O and event-driven architecture.

NodeJS’s ability to handle concurrent connections, speed, and scalability have made it a preferred choice for developers building real-time applications like chat, gaming, and collaboration tools.

Its extensive module ecosystem (NPM) and support for asynchronous programming have solidified its popularity among developers.

Benefits NodeJS App Development:

  • Event-Driven Architecture:
    NodeJS’s event-driven, non-blocking I/O model ensures efficient and scalable performance.
  • Real-Time Applications:
    NodeJS app development excels in building real-time applications like chat, gaming, and collaboration tools.
  • Large Module Ecosystem:
    Its extensive module ecosystem (NPM) offers a wide range of pre-built functionalities.
  • Non-Blocking I/O:
    NodeJS framework features a non-blocking I/O model that enables concurrent connections, enhancing application responsiveness.
  • Speed and Scalability:
    The development framework’s performance and scalability make it ideal for handling large numbers of simultaneous connections.

Ruby on Rails:

Ruby on Rails, released in 2004 by David Heinemeier Hansson, was developed to provide a framework that follows the principles of convention over configuration.

Are you looking for a Full-Stack developer

Contact Us

It offers rapid development capabilities and encourages clean and readable code.

Ruby on Rails gained popularity for its developer-friendly code, built-in database migration tools, and active community support.

Its focus on developer happiness, rapid development, and elegant syntax has made it a favoured choice among startups and small businesses.

Benefits of Ruby-on-Rails App Development:

  • Developer-Friendly Code:
    Ruby-on-Rails development promotes clean and readable code, making development more enjoyable.
  • Seamless Database Migration:
    It includes built-in database migration tools for easy data management.
  • Active Community:
    It is supported by a large and active community of Ruby-on-Rails developers who continuously contribute to the framework’s improvement.
  • Built-In Testing Support:
    Ruby-on-Rails has built-in testing support which encourages testing, ensuring reliable and bug-free applications.
  • Elegant Syntax:
    Ruby-on-Rails’ elegant syntax simplifies code maintenance and readability.

Top Things to Consider Before Choosing a Web Development Framework:

While choosing the right web development framework, consider the following factors:

  1. Project Requirements:
    Evaluate the project’s complexity and choose a framework that aligns with your application’s needs.
  2. Learning Curve:
    Consider the ease of learning the framework, especially if you have a team of developers with varying skill levels.
  3. Scalability:
    Choose a framework that can scale with your application’s growth and handle increasing traffic.
  4. Community Support:
    Ensure the framework has an active community that can provide updates, support, and solutions to issues.
  5. Security:
    Evaluate the framework’s security features and assess its ability to handle potential vulnerabilities.
  6. Performance:
    Look for frameworks that prioritize performance and optimize application speed.
  7. Documentation:
    Consider the quality and comprehensiveness of the framework’s official documentation.
  8. Third-Party Integration:
    Check if the framework supports integration with third-party tools and libraries.
  9. Development Speed:
    Choose a framework that allows for rapid development without sacrificing code quality.
  10. Long-Term Viability:
    Select a framework with a strong user base and continuous development support for long-term success.

Conclusion:

Full-stack development frameworks have revolutionized the way web applications are built, providing developers with powerful tools to create dynamic and robust web apps.

As the demand for feature-rich and interactive web experiences continues to grow, these frameworks have become essential for modern web development.

Whether it’s front-end frameworks like ReactJS, Angular, and VueJS or back-end frameworks like Django, Flask, and Laravel, each offers unique advantages and empowers developers to build web applications that meet the demands of today’s digital world.

When selecting a web development framework, consider your project’s requirements, scalability, security, and the community’s support to ensure a successful and efficient development process.

With the right framework in hand, you’ll be on your way to crafting exceptional web applications that stand out in the digital landscape of 2023 and beyond.

Frequently Asked Questions

How much time does it take to build a web app?

The time to build a web app depends on various factors, including complexity, scope, development team size, and chosen frameworks. On average, it may take several weeks to several months to complete a web app.

Can I use multiple frameworks for a single web app?

Yes, it’s possible to use multiple frameworks within a web app. Front-end and back-end frameworks can work harmoniously together, allowing developers to leverage the strengths of each framework for different aspects of the application.

How can I choose the right framework for my project?

Consider factors like project requirements, team expertise, scalability, community support, and documentation when choosing a framework. Conduct research, try out demos, and seek recommendations to find the best fit for your specific project needs.

What are the key benefits of full-stack development?

Full-stack development offers several advantages, including streamlined development, faster time-to-market, efficient team collaboration, reduced dependency on external teams, and a comprehensive understanding of the entire application stack.

How To Manage API Request with AXIOS on a React Native App

APIs can make your life a whole lot easier. With an API, you can send requests to other services and get responses without having to build those requests and responses yourself. But building an API isn’t as simple as it sounds. It requires careful planning, testing, and debugging.

If you’re building an API for the first time, it can feel like an impossible mountain to climb. That’s where APIs like Axios come in. It has a great API and lots of helpful features. Here in this article you’ll understand how to use Axios to manage API requests in your React Native app.

What is AXIOS?

Axios is one of the easiest HTTP clients to learn and use. Making an API request is as simple as passing a configuration object to Axios or invoking the appropriate method with the necessary arguments. You will learn the basics of Axios in this section.

Configuring Axios

Type following command on terminal window to install Axios:

NPM Install Axios

How to make requests to an API using Axios

Making a call to an API using Axios, you can pass a configuration object to Axios or invoke a method for the corresponding CRUD operations.

Never miss an update from us. Join 10,000+ marketers and leaders.

For example, you can make a GET request to the /api/users endpoint in one of the following two ways:

[code language=”css”]</pre>
import axios from ‘axios’;
const baseUrl = ‘https://reqres.in’;
// Passing configuration object to axios
axios({
method: ‘get’,
url: `${baseUrl}/api/users/1`,
}).then((response) => {
console.log("<<<<<< Passing configuration object to axios >>>>>>", response.data.data);
});

// Invoking get method to perform a GET request
axios.get(`${baseUrl}/api/users/1`).then((response) => {
console.log("<<<<<< Invoking get method to perform a GET request >>>>>>", response.data.data);
});
[/code]

There are several other fields such as baseURL, transformRequest, transformResponse, and headers, among others, which you can include in the configuration object you pass to Axios.

[code language=”css”]</pre>
// Passing configuration object to axios
const fetchUserFirst = async () => {
const configurationObject = {
method: ‘get’,
url: `${baseUrl}/api/users/1`,
};
const response = await axios(configurationObject);
console.log("<<<<<< Fetch User First >>>>>>", response.data.data);
};

// Invoking get method to perform a GET request
const fetchUserSecond = async () => {
const url = `${baseUrl}/api/users/2`;
const response = await axios.get(url);
console.log("<<<<<< Fetch User Second >>>>>>", response.data.data);
};
[/code]

How to make multiple concurrent API requests using Axios

We can use the Promise.all or Promise.allSettled method of the Promise API with Axios to make multiple concurrent API requests from a React Native application.

[code language=”css”]
const concurrentRequests = [
axios.get(`${baseUrl}/api/users/1`),
axios.get(`${baseUrl}/api/users/2`),
axios.get(`${baseUrl}/api/users/3`),
];
// Using Promise.all
Promise.all(concurrentRequests)
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
// Using Promise.allSettled
Promise.allSettled(concurrentRequests)
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
[/code]

How to abort network request in Axios

Axios provides functionality for aborting network requests. A typical use case of this feature in React Native is the cancellation of network requests in the use effect hook when a component is unmounted while data is still in flight.

[code language=”css”]
useEffect(() => {
const source = axios.CancelToken.source();
const url = `${baseUrl}/api/users/${userId}`;
const fetchUsers = async () => {
try {
const response = await axios.get(url, { cancelToken: source.token });
console.log(response.data);
} catch (error) {
if(axios.isCancel(error)){
console.log(‘Data fetching cancelled’);
}else{
// Handle error
}
}
};
fetchUsers();
return () => source.cancel("Data fetching cancelled");
}, [userId]);
[/code]

How to create an instance of Axios

You can also create an instance of Axios with a custom configuration. Axios will merge the configuration object passed while creating the instance with the configuration passed to the instance method:

[code language=”css”]
const axiosInstance = axios.create({ baseURL: ‘https://reqres.in/’ });
axiosInstance.get(‘api/users/1’).then((response) => {
console.log(response.data);
});
[/code]

How to make GET request using Axios in React Native

Make a GET request to the /api/users endpoint to retrieve a user and store the user ID in state as shown in the code snippet below. You can change the user ID inside the onPress event handler attached to the Load User button. Changing the user ID will trigger a GET request to the API inside the useEffect hook.

After triggering a network request, we display a loading indicator on the screen. If we fetch the data successfully, we update state and remove the loading indicator. If we fail to retrieve the data for some reason, we stop the loading indicator and display an appropriate error message.

We abort the network request in the clean-up function if the user decides to close the app before getting a response from the server. Check the return value of the effect function in the useEffect hook. Following is the code in the App.js component:

[code language=”css”]
import axios from "axios";
import React, { useState, useEffect } from "react";
import {
StyleSheet,
Text,
ScrollView,
View,
Button,
Image,
Platform,
} from "react-native";
import Constants from "expo-constants";
const baseUrl = "https://reqres.in";
function User({ userObject }) {
return (
<View>
<Image
source={{ uri: userObject.avatar }}
style={{ width: 128, height: 128, borderRadius: 64 }}
/>
<Text style={{ textAlign: "center", color: "white" }}>
{`${userObject.first_name} ${userObject.last_name}`}
</Text>
</View>
);
}
export default function App() {
const [userId, setUserId] = useState(1);
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [hasError, setErrorFlag] = useState(false);
const changeUserIdHandler = () => {
setUserId((userId) => (userId === 3 ? 1 : userId + 1));
};
useEffect(() => {
const source = axios.CancelToken.source();
const url = `${baseUrl}/api/users/${userId}`;
const fetchUsers = async () => {
try {
setIsLoading(true);
const response = await axios.get(url, { cancelToken: source.token });
if (response.status === 200) {
setUser(response.data.data);
setIsLoading(false);
return;
} else {
throw new Error("Failed to fetch users");
}
} catch (error) {
if(axios.isCancel(error)){
console.log(‘Data fetching cancelled’);
}else{
setErrorFlag(true);
setIsLoading(false);
}
}
};
fetchUsers();
return () => source.cancel("Data fetching cancelled");
}, [userId]);
return (
<ScrollView contentContainerStyle={styles.container}>
<View style={styles.wrapperStyle}>
{!isLoading && !hasError && user && <User userObject={user} />}
</View>
<View style={styles.wrapperStyle}>
{isLoading && <Text> Loading </Text>}
{!isLoading && hasError && <Text> An error has occurred </Text>}
</View>
<View>
<Button
title="Load user"
onPress={changeUserIdHandler}
disabled={isLoading}
style={styles.buttonStyles}
/>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "dodgerblue",
alignItems: "center",
justifyContent: "center",
marginTop: Platform.OS === "ios" ? 0 : Constants.statusBarHeight,
},
wrapperStyle: {
minHeight: 128,
},
buttonStyles: {
padding: 100,
},
});
[/code]

How to make a POST request

POST is the HTTP method you use to send data to the server for updating or creating a resource. Making a POST request in Axios is similar to making a GET request. Most of the time, POST requests are made with user-generated data submitted using a form. Data requires validation on the client side before it is submitted.

Two main React packages for managing forms are Formik and React Hook Form. React Native form for the user’s full name and email in the code snippet below. Both TextInput components are controlled components.

After clicking the submit button, the TextInput fields and the submit button are disabled before you display a message to show you are creating the resource. Disabling the submit button ensures the user doesn’t make multiple submissions. After successfully submitting a POST request, you display a success message to the user:

[code language=”css”]
import axios from "axios";
import React, { useState, useEffect } from "react";
import {
StyleSheet,
Text,
ScrollView,
View,
Button,
Image,
Platform,
} from "react-native";
import Constants from "expo-constants";
const baseUrl = "https://reqres.in";
function User({ userObject }) {
return (
<View>
<Image
source={{ uri: userObject.avatar }}
style={{ width: 128, height: 128, borderRadius: 64 }}
/>
<Text style={{ textAlign: "center", color: "white" }}>
{`${userObject.first_name} ${userObject.last_name}`}
</Text>
</View>
);
}
export default function App() {
const [userId, setUserId] = useState(1);
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [hasError, setErrorFlag] = useState(false);
const changeUserIdHandler = () => {
setUserId((userId) => (userId === 3 ? 1 : userId + 1));
};
useEffect(() => {
const source = axios.CancelToken.source();
const url = `${baseUrl}/api/users/${userId}`;
const fetchUsers = async () => {
try {
setIsLoading(true);
const response = await axios.get(url, { cancelToken: source.token });
if (response.status === 200) {
setUser(response.data.data);
setIsLoading(false);
return;
} else {
throw new Error("Failed to fetch users");
}
} catch (error) {
if(axios.isCancel(error)){
console.log(‘Data fetching cancelled’);
}else{
setErrorFlag(true);
setIsLoading(false);
}
}
};
fetchUsers();
return () => source.cancel("Data fetching cancelled");
}, [userId]);
return (
<ScrollView contentContainerStyle={styles.container}>
<View style={styles.wrapperStyle}>
{!isLoading && !hasError && user && <User userObject={user} />}
</View>
<View style={styles.wrapperStyle}>
{isLoading && <Text> Loading </Text>}
{!isLoading && hasError && <Text> An error has occurred </Text>}
</View>
<View>
<Button
title="Load user"
onPress={changeUserIdHandler}
disabled={isLoading}
style={styles.buttonStyles}
/>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "dodgerblue",
alignItems: "center",
justifyContent: "center",
marginTop: Platform.OS === "ios" ? 0 : Constants.statusBarHeight,
},
wrapperStyle: {
minHeight: 128,
},
buttonStyles: {
padding: 100,
},
});
[/code]

How to make a DELETE request

DELETE requests using Axios the same way you make POST and PUT requests. DELETE request will delete a resource from the server side. You can replace the onSubmitFormHandler of the code for making a POST request with the event handler below to make a DELETE request.

[code language=”css”]
const onSubmitFormHandler = async (event) => {
if (!fullName.trim() || !email.trim()) {
alert("Name or Email is invalid");
return;
}
setIsLoading(true);
try {
const response = await axios.delete(`${baseUrl}/api/users/2`, {
fullName,
email,
});
if (response.status === 204) {
alert(` You have deleted: ${JSON.stringify(response.data)}`);
setIsLoading(false);
setFullName(”);
setEmail(”);
} else {
throw new Error("Failed to delete resource");
}
} catch (error) {
alert("Failed to delete resource");
setIsLoading(false);
}
};
[/code]

How to make a PUT request

Updating a resource requires either the PUT or PATCH method. If a resource exists, using the PUT method completely overwrites it, and creates a new resource if it doesn’t. PATCH makes partial updates to the resource if it exists and does nothing if it doesn’t.

Making a PUT request to an API is similar to making a POST request. The only difference is the configuration object passed to Axios, or the HTTP method needed to invoke to make a PUT request to the API. Replace the onSubmitFormHandler of the POST request with the code below to make a PUT request.

[code language=”css”]</pre>
const onSubmitFormHandler = (event) => {
if (!fullName.trim() || !email.trim()) {
alert("Name or Email is invalid");
return;
}
setIsLoading(true);
const configurationObject = {
url: `${baseUrl}/api/users/2`,
method: "PUT",
data: { fullName, email },
};
axios(configurationObject)
.then((response) => {
if (response.status === 200) {
alert(` You have updated: ${JSON.stringify(response.data)}`);
setIsLoading(false);
setFullName("");
setEmail("");
} else {
throw new Error("An error has occurred");
}
})
.catch((error) => {
alert("An error has occurred");
setIsLoading(false);
});
};
[/code]

How to handle errors

React-error-boundary (Simple reusable React error boundary component) is a simple reusable component based on React error boundary API that provides a wrapper around your components and automatically catches all errors from the children’s components hierarchy, and also provides a great way to recover your component tree. Create an Errorhandler component like the following code snippet.

[code language=”css”]</pre>
import * as React from "react";
import { ErrorBoundary } from "react-error-boundary";
import { View, StyleSheet, Button } from "react-native";
import { Text } from "components";
const myErrorHandler = (error: Error) => {
// Do something with the error
function ErrorFallback({ resetErrorBoundary }) {
return (
<View style={[styles.container]}>
<View>
<Text> Something went wrong: </Text>
<Button title="try Again" onPress={resetErrorBoundary} />
</View>
</View>
);
}
export const ErrorHandler = ({ children }: { children: React.ReactNode }) => (
<ErrorBoundary FallbackComponent={ErrorFallback} onError={myErrorHandler}>
{children}
</ErrorBoundary>
);
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "column",
alignItems: "stretch",
justifyContent: "center",
alignContent: "center",
paddingHorizontal: 12,
},
});
[/code]

Here you can find the sample code in this Github repository

Best Practices for using AXIOS

Global config

Set up a global configuration that handles all application requests using a standard configuration that is set through a default object that ships with Axios. This object contains:

    • baseURL: A relative URL that acts as a prefix to all requests, and each request can append the URL
    • headers: Custom headers that can be set based on the requests
    • Timeout: The point at which the request is aborted, usually measured in milliseconds. The default value is 0, meaning it’s not applicable.
    • With Credentials: Indicates whether or not cross-site Access-Control requests should be made using credentials. The default is false.
    • Response Type: Indicates the type of data that the server will return, with options including json (default), arraybuffer, document, text, and stream.
    • Response Encoding: Indicates encoding to use for decoding responses. The default value is utf8.
    • xsrfCookieName: The name of the cookie to use as a value for XSRF token, the default value is XSRF-TOKEN.
    • xsrfHeaderName: The name of the HTTP header that carries the XSRF token value. The default value is X-XSRF-TOKEN.
    • maxContentLength: Defines the max size of the HTTP response content in bytes allowed
    • maxBodyLength: Defines the max size of the HTTP request content in bytes allowed

Most of the time, only be using baseURL, header, and maybe timeout. The rest of them are less frequently needed as they have smart defaults, but it’s nice to know they are there in case you need to fix up requests.

Are you looking for a React Native developer

Contact Us

This is the DRYness at work. For each request, we don’t have to repeat the baseURL of our API or repeat important headers that we might need on every request.

Custom instance

Setting up a “custom instance” is similar to a global config, but scoped to specified components so that it’s still a DRY technique, but with hierarchy. Set up a custom instance in a new file (Ex: authAxios.js) and import it into the “concern” components.

[code language=”css”]
// authAxios.js
import axios from ‘axios’;
const customInstance = axios.create ({
baseURL : ‘https://axios-app.firebaseio.com’
})
customInstance.defaults.headers.post[‘Accept’] = ‘application/json’
// Or like this…
const customInstance = axios.create ({
baseURL : ‘https://axios-app.firebaseio.com’,
headers: {‘Accept’: ‘application/json’}
})
[/code]

Then import this file into the “concern” components:

[code language=”css”]

// form.js component import from our custom instance
import axios from ‘./authAxios’;
export default {
methods : {
onSubmit () {
axios.post(‘/users.json’, formData)
.then(res => console.log(res))
.catch(error => console.log(error))
}
}
}
[/code]

Axios Verbs

Group the Axios HTTP verbs, like GET, POST, DELETE, and PATCH, in the base config file, as below.

[code language=”css”]</pre>
export function getRequest(URL) {

return axiosClient.get(`/${URL}`).then(response => response);

}

export function postRequest(URL, payload) {

return axiosClient.post(`/${URL}`, payload).then(response => response);

}

export function patchRequest(URL, payload) {

return axiosClient.patch(`/${URL}`, payload).then(response => response);

}

export function deleteRequest(URL) {

return axiosClient.delete(`/${URL}`).then(response => response);
<pre>}
[/code]

Now import the custom functions directly wherever needed to make an API request, as in the code below.

[code language=”css”]</pre>
import { getRequest } from ‘axiosClient’;

async function fetchUser() {

try {

const user = await getRequest(‘users’);

} catch(error) {

//Log errors

}
<pre>}
[/code]

Interceptors

  • Interceptors helps with cases where the global config or custom instance might be too generic, in the sense that if you set up a header within their objects, it applies to the header of every request within the affected components. Interceptors have the ability to change any object properties on the fly. For instance, we can send a different header based on any condition we choose within the interceptor.
  • Interceptors can be in the main.js file or a custom instance file. Requests are intercepted after they’ve been sent out and allow us to change how the response is handled.

[code language=”css”]
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent, like we’re inserting a timeout for only requests with a particular baseURL
if (config.baseURL === ‘https://axios-app.firebaseio.com/users.json’) {
config.timeout = 4000
} else {
return config
}
console.log (config)
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data like console.log, change header, or as we did here just added a conditional behaviour, to change the route or pop up an alert box, based on the reponse status
if (response.status === 200 || response.status 201) {
router.replace(‘homepage’) }
else {
alert(‘Unusual behaviour’)
}
console.log(response)
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
[/code]

Conclusion

For most of your HTTP communication needs, Axios provides an easy-to-use API in a compact package.

There are some alternative libraries for HTTP communication, such as ky, a tiny and elegant HTTP client based on window.fetch; superagent, a small, progressive client-side HTTP request library based on XMLHttpRequest.

But Axios is a better solution for applications with a lot of HTTP requests and for those that need good error handling or HTTP interceptions.

We at Andolasoft has long expertise on API Request solution with AXIOS on a React Native App. We have highly experienced React Native and React developers to help you for the same. Book a free consultation on your issues.