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.

How To Integrate JWT in Python Django REST Framework?

Django REST Framework is one of the most popular Django web frameworks that has been used to build many successful projects. It provides a simple and easy-to-use interface for designing APIs and JSON web services, which is quite popular among startups. When working with the REST framework in Python, there are a few ways you can implement the JSON Web Token (JWT) type of authentication.

What Is JWT?

JWT is an encoded JSON string that is passed in headers to authenticate requests. It is usually obtained by hashing JSON data with a secret key. This means that the server doesn’t need to query the database every time to retrieve the user associated with a given token.

How JSON Web Tokens Work

When a user successfully logs in using their credentials, a JSON Web Token is obtained and saved in local storage. Whenever the user wants to access a protected URL, the token is sent in the header of the request. The server then checks for a valid JWT in the Authorization header, and if found, the user will be allowed access.

A typical content header will look like this:

[code language=”css”]
Authorization: Bearer gdh676hghu
[/code]

Work Flow of JWT

JWT Diagram

Advantages of JWT

  • No Session to Manage (stateless)
  • Portable
  • No Cookies Required, So It’s Very Mobile Friendly
  • Good Performance
  • JWT helps in securing APIs

Django REST Framework

Django REST framework (DRF) is an open source, mature and well supported Python/Django library that aims at building sophisticated web APIs. It is a flexible and fully-featured toolkit with modular and customizable architecture that makes possible development of both simple, turn-key API endpoints and complicated REST constructs.

Main Advantages of Django REST framework

  • Simplicity, flexibility, quality, and test coverage of source code.
  • Powerful serialization engine compatible with both ORM and non-ORM data sources.
  • Pluggable and easy to customize emitters, parsers, validators and authenticators.
  • Generic classes for CRUD operations.
  • Clean, simple, views for Resources, using Django’s new class based views.
  • Support for Model Resources with out-of-the-box default implementations and input validation (optional support for forms as input validation).
  • HTTP response handling, content type negotiation using HTTP Accept headers.

Implementing JWT in Django REST Framework

Django REST Framework comes with various default Authentication Classes. Basic Authentication, Session Authentication, and Token Authentication to name a few.

Token-based authentication is the most preferred method of implementing authentication in modern APIs. In this mechanism, the server generates a token for the authenticated user and the user has to send the token along with all the HTTP requests to identify themselves.

Install DRF and Django-rest-framework-jwt using pip

[code language=”css”]
pip install djangorestframework

pip install djangorestframework-jwt

pip install django
[/code]

In order to use JWT, we need to configure Django-rest-framework permissions to accept JSON Web Tokens.

In the settings.py file, add the following configurations:

[code language=”css”]
REST_FRAMEWORK = {

‘DEFAULT_AUTHENTICATION_CLASSES’: (

‘rest_framework_jwt.authentication.JSONWebTokenAuthentication’,

),

}
[/code]

Now add JWT API endpoint to the settings.py file as below

[code language=”css”]
from django.urls import path, include

from rest_framework_simplejwt import views as jwt_views

&nbsp;

urlpatterns = [

path(‘api/token/’,

jwt_views.TokenObtainPairView.as_view(),

name =’token_obtain_pair’),

path(‘api/token/refresh/’,

jwt_views.TokenRefreshView.as_view(),

name =’token_refresh’),

path(”, include(‘app.urls’)),

]
[/code]

The above endpoint will be used to generate and refresh the JWT token on every API call.

We will make use of the Django-REST Framework JWT Python module we installed at the beginning of this tutorial. It adds JWT authentication support for Django Rest Framework apps.

Let’s define some configuration parameters for our tokens and how they are generated in the settings.py file.

[code language=”css”]
import datetime

JWT_AUTH = {

&nbsp;

‘JWT_VERIFY’: True,

‘JWT_VERIFY_EXPIRATION’: True,

‘JWT_EXPIRATION_DELTA’: datetime.timedelta(seconds=3000),

‘JWT_AUTH_HEADER_PREFIX’: ‘Bearer’,

}
[/code]

  • JWT_VERIFY: It will raise a jwt. Decode Error if the secret is wrong.
  • JWT_VERIFY_EXPIRATION: Sets the expiration to True, meaning Tokens will expire after a period of time. The default time is five minutes.
  • JWT_AUTH_HEADER_PREFIX: The Authorization header value prefix that is required to be sent together with the token. We have set it as Bearer, and the default is JWT

Now you can use the JWT payload in your authentication method. Go to the views.py file and add the following code

[code language=”css”]
def authenticate_user(request):

email = request.data[’email’]

password = request.data[‘password’]

&nbsp;

user = User.objects.get(email=email, password=password)

if user:

payload = jwt_payload_handler(user)

token = jwt.encode(payload, settings.SECRET_KEY)

user_details = {}

user_details[‘name’] = "%s %s" % ( user.first_name, user.last_name)

user_details[‘token’] = token

user_logged_in.send(sender=user.__class__,request=request, user=user)

return Response(user_details, status=status.HTTP_200_OK)

[/code]

Every time the user wants to make an API request, they have to send the token in auth Headers in order to authenticate the request. You can test the API endpoint using Postman or any other API testing tools.

You can check the JWT token by using any of the PI test tools like Postman. Below is the screenshot of using postman to call the JWT API

JWTYou can find out the source code for the demo project here at Github

Conclusion

JWTs are the best way to securely exchange information between front-end and backend because they can be signed, which means we can be sure that the senders are who they say they are. The structure of a JWT allows us to verify that the content hasn’t been tampered with.

JWT makes the process of user authentication on the web much easier, providing a simpler way to exchange information between a server and a client.

The Django REST Framework is a RESTful framework for developing Django applications. It provides a high-level view on how to develop RESTful web services in Django.

An Introduction To BuildContext In Flutter and It’s Importance?

BuildContext is the object that stores information about the current build. It provides information such as the minimum and maximum supported Flutter version, the device’s screen size and pixel density, the currently active theme, and more.

The BuildContext is the set of inputs that Flutter uses to create an instance of a widget. It includes properties on the Android and iOS platforms, as well as properties related to the current device and environment.

It can be used to customize the behavior and appearance of your widget, but it’s important to understand how it works in order to avoid any issues.

For instance, you can use BuildContext.host () to get a string that specifies the current app’s host name. You can also use BuildContext.local (context).emulator so you can set up an emulator for testing your app on different devices without needing to change settings in Android Studio every time you want to switch emulators.

Flutter is one of the hottest technologies for cross-platform mobile development. It has been described as a new contender in the app development industry, competing with traditional frameworks like React Native and Xamarin.

Flutter builds on Google’s own Dart programming language and provides a library of scalable, customizable UI widgets to help developers build beautiful native interfaces that run across all platforms. It has been designed to help developers build high-quality, natively compiled apps that run on both Android and iOS from one codebase.

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

What is a BuildContext?

The BuildContext is a locator that is used to point the location of the widget in the widget tree.

In Flutter we have to create widgets through the build method & we have to pass the BuildContext as an argument to the build method.

Each BuildContext is different for every widget. Each widget you create has its own BuildContext and they can locate themselves in the widget tree or reach out to the nearest widget.

This is how we create a widget

[code language=”css”]
Widget build (BuildContext context)=&gt; MyAwesomeWidget();
[/code]

Flutter widget tree

Everything in Flutter is a widget. Whether it is a container, providers, text, button, image etc. everything is a widget, whether it reflects the UI in the app or not.

The UI or display in Flutter comprises stacks of widgets popularly called a widget tree. Each component is responsible for a small unit of the entire UI.

Flutter widget tree

The above image is an example of a widget tree in Flutter. We can observe that every widget has its own place in the widget tree i.e. the Button widget is under column widget.

Widgets are only visible to its BuildContext or to its parent’s BuildContext. That means we can locate the parent widget from the child widget. For the above image tree structure we can get Scaffold from Container by going up:

[code language=”css”]
context.ancestorWidgetOfExactType(Scaffold)
[/code]

You can also locate a child widget from a parent widget and for that, we use Inherited Widgets.

There are three main trees in Flutter:

  1. Widget
  2. Element
  3. Render

Widget

Widgets are immutable, they represent the structure for RenderObjects Fluorescence is optimized, which can easily create and destroy widgets without any significant performance implications.

The same can’t be said for RenderObjects.

Element

In the middle of Widgets and RenderObjects sits elements. These act as the glue between the immutable widget layer and the mutable render layer.

As the configuration of a widget changes (for example, the user calls the set state that triggers a rebuild), the element notices incoming changes and says to the corresponding render object,

“Hey! Please update. ”

Render

RenderObjects are what the visual pieces on the screen correspond to. Their purpose is to define areas on the screen regarding their spatial dimensions. They are referenced by the element. As a consequence we are dealing with another (third) tree here: the RenderObjects together form a tree which is called Render Tree whose root node is a RenderView (being a variant of a RenderObject). The RenderObject, on the other hand, are mutable objects that do the heavy lifting of turning the configuration supplied from widgets into pixels users can see and interact with on the screen.

Unlike widgets that are cheap and can safely be created and destroyed without any significant performance implications, the same cannot be said for RenderObjects.

For this reason, whenever the configuration of a widget changes, the framework looks at the change and updates the associated RenderObject instead of creating a new one each time.

Conclusion

Understanding BuildContext is very crucial to develop applications in Flutter. This improves our knowledge on how Flutter works and helps to build apps confidently.

BuildContext is a facade that provides a consistent API for implementing custom layouts and animations. The code is platform-specific, but the abstraction weaves some of the underlying platform-specific logic out of sight. BuildContext also helps reduce the need to know about the underlying platform details when implementing custom layouts and animations.

I’ve worked with the team at Andolasoft on multiple websites. They are professional, responsive, & easy to work with. I’ve had great experiences & would recommend their services to anyone.

Ruthie Miller, Sr. Mktg. Specialist

Salesforce, Houston, Texas

LEARN MORE

Flutter is an open-source mobile app SDK that is used to make a high-quality app with a beautiful and consistent user experience. Unlike native mobile development, Flutter does not require that an app has a single, complete codebase but instead lets you mix and match code for different platforms. It also provides a rich set of pre-built widgets and allows for shared state.

The BuildContext is the context in which the Flutter app is running and is used for determining where to find resources and strings. It can be thought of as the environment in which the app is being used. Flutter provides an abstract class called BuildContext that handles the loading of resources, without requiring the developer to use hardcoded paths. This abstraction is one of the things that makes flutter so easy to use.

Flutter provides a set of high-level classes to help flutter developers build reactive user interfaces. Are you looking to develop an application in flutter framework? Let’s discuss

How To Use JavaScript Promises and Fetch API

As an interpreted language, JavaScript executes code line by line. However, it does not wait for the dependent code to execute before executing the next line.

To achieve this feature JavaScript introduces the callback function. Basically this is associated with the asynchronous operations in JavaScript.

But the issue with the callback function is if we have more than one asynchronous operation running at the same time. So it became hell to manage the code using the callback functions.

The problems are

  • Hard to understand the codes because the code becomes lengthier and nested structure.
  • Hard to manage the codes, because it is not clear which callbacks are called when and also there are so many callbacks to write to perform a particular task.
  • Also need not satisfy all the requirements

Here JavaScript introduces the concept of Promises.

JavaScript promises represent the eventual completion or failure of asynchronous operations. Promises are either resolved or rejected. Hence, when it resolves or rejects multiple asynchronous operations, it returns either success or an error.

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

Chaining Promises is provided to handle multiple asynchronous operations. So the code here is manageable and easy to understand. For your understanding, here are some examples of callbacks and promises.

Callbacks

[code language=”css”]
function validateMoney(money){

var interest = 100;

if(money){

return money+interest;

}else{

return money;

}

}

function getInterestMoney(money, callback) {

if (typeof money !== ‘number’) {

return callback(‘money is not a number’);

} else {

return callback(money)

}

}

const money = getInterestMoney(1200, validateMoney);

console.log(money);
[/code]

Promises:

[code language=”css”]
function getInterestMoney(money) {

return new Promise((resolve, reject) =&amp;gt; {

if (typeof money !== ‘number’) {

reject(new Error(‘money is not a number’))

} else {

var interest = 100;

money = money+interest;

resolve(money);

}

})

}

getInterestMoney(1200)

.then((money) =&amp;gt; {

console.log(money);

}).catch((error) =&amp;gt; {

console.error(error);

});
[/code]

Fetch API:

Fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

Here is an example of the fetch api

[code language=”css”]
fetch(‘./api/some.json’)

.then(

function(response) {

if (response.status !== 200) {

console.log(‘Looks like there was a problem. Status Code: ‘ +

response.status);

return;

}

// Examine the text in the response

response.json().then(function(data) {

console.log(data);

});
[/code]

Chaining Promises

One of the great features of promises is the ability to chain them together. For fetch, this allows you to share logic across fetch requests.

Are you looking for a JavaScript developer

Contact Us

If you are working with a JSON API, you’ll need to check the status and parse the JSON for each response. You can simplify your code by defining the status and JSON parsing in separate functions which return promises, freeing you to only worry about handling the final data and the error case.

[code language=”css”]
function status(response) {

if (response.status &amp;gt;= 200 &amp;amp;&amp;amp; response.status &amp;lt; 300) {

return Promise.resolve(response)

} else {

return Promise.reject(new Error(response.statusText))

}

}

function json(response) {

return response.json()

}

fetch(‘users.json’)

.then(status)

.then(json)

.then(function(data) {

console.log(‘Request succeeded with JSON response’, data);

}).catch(function(error) {

console.log(‘Request failed’, error);

});
[/code]

Hope the aforementioned guidelines will assist you in effectively utilizing JavaScript Promises and the Fetch API. For further insights and detailed information, recommend referring to the resources available on Google Developers.

If you require expert assistance with JavaScript development, you may consider engaging the services of Andolasoft’s experienced JavaScript developers

Let’s discuss.

How To Use Service Oriented Architecture In IOS Swift

Talking about software and application architecture is always fascinating. In order to run smoothly, everyone needs to follow certain processes and principles. It’s always good to have clean, reusable, and bug-free code, and Service Oriented Architecture plays a crucial role in implementing that.

Service-oriented architecture makes our life easier by structuring the interaction between the high-level and lower-level implementations while keeping our code reusable and structured.

So now the question arises, what exactly service oriented architecture (SOA) is?

What is Service Oriented Architecture?

Service Oriented Architecture is an architecture pattern that consolidates functionalities and business logic in such a way that services can be injected into view controllers for use. This process easily and cleanly separates the front end user interface and the back end programming and business logic.

Service Oriented Architecture(Source – orientsoftware.com)

Why Service Oriented Architecture

Let’s take a look at a few benefits of Service-Oriented Architecture. The most important benefit is managing business changes quickly and supporting newer channels of customer interaction,

  • Improvement in the flow of information.
  • Flexibility in the functionalities.
  • Reduced cost in the developmental cycle.
  • Easy to manage.
  • Improvement in data confidentiality and hence more reliability.
  • Quicker system upgrades.
  • Testing has improved.
  • Re-usability of codes.
  • A standard form of communication is established.
  • Allowing scalability to meet the needs of clients.

Why Service Oriented Architecture(Source – orientsoftware.com)

There are many patterns which can be used on the iOS development like MVC, MVVM, MVP, or VIPER. These architectural patterns handle only the higher level (UI) of our application. But soon after, we also need to implement the network managers, API clients, data sources, persistence containers, and so on.

In the following folder structure and piece of code we can view, how to implement a service-oriented architecture (SOA) in our iOS app development.

Are you looking for a iOS developer

Contact Us

Folder Structure

  • Classes
    • DataAccessLayer
    • PresentationLayer
    • WebAccessLayer
    • BusinessLayer
  1. The DataAccessLayer folder contains the persistence layer folders
    1. DBHelper
    2. CoreDataManager
    3. CoreDataObject
  2. PresentationLayer folder contains the user interface layer folders
    1. ViewControllers
    2. CustomCells
    3. CustomViews
  3. WebAccessLayer folder contains the
    1. APIManager
  4. BusinessLayer folder contains the business logic
    1. BusinessLogic
    2. BusinessObj

Sample Code

1. DBHelper

[code language=”css”]
func insertSportsToLocalDB(arrSports:NSMutableArray) -&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Void {
}
[/code]

2. CoreDataManager

[code language=”css”]
funcfetchPrivacySettingData() -&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Array&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;Any&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; {
do {
# fetch result from local db
} catchlet error asNSError {
# handle the sql exception
}
return results!
}
[/code]

3. CoreDataObject

[code language=”css”]
extensionCourts {

@nonobjc public class funcfetchRequest() -&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;NSFetchRequest&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;Courts&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; {
returnNSFetchRequest&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;Courts&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;(entityName: "Courts");
}

@NSManaged public varvenue_id: String?


}
[/code]

4. ViewControllers

[code language=”css”]
funcserviceCallToSaveGame() -&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Void {
#show activity indicator
#prepare the service call request
letparams = ["user_id" : UserDefaults.standard.object(forKey: STRING_CONSTANT.KEY_USERID)]
#call the api manager web service call method
APIManager.sharedInstance.serviceCallRelatedToVenue(url: _API_PATH.kCreatePOI
param: params)(
#hide the indicator

}
}
[/code]

5. CustomCells

[code language=”css”]
a. CustomCells contains listview of user interface
[/code]

6. CustomViews

[code language=”css”]
funcdesignCustomListPopUp(withDataarrLists: Array&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;Any&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;) -&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Void {

}
[/code]

7. APIManager

[code language=”css”]
funcserviceCallToGetProfile(withPathpath:String, withDataparam:[String:Any], withCompletionHandler completion:@escaping (AnyObject?) -&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Void){

Alamofire.request(requestURL, method: .post, parameters: param, encoding: URLEncoding.methodDependent, headers: nil).responseJSON { (responseJson) in
}

}
[/code]

Advantages of Service-Oriented Architecture (SOA)

1. Reliability

With small and independent services in the SOA, it becomes easier to test and debug the applications instead of debugging the massive code chunks, which makes this highly reliable.

2. Location Independence

Services are located through the service registry and can be accessed through Uniform Resource Locator (URL), therefore they can change their location over time without interrupting consumer experience on the system while making SOA location independent.

3. Scalability

As SOA enables services to run across multiple platforms, programming languages and services, that is, services of the service-oriented architecture operate on different servers within an environment, which increases its scalability.

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

4. Platform Independence

Service-Oriented Architecture permits the development of the complex application by integrating different services opted from different sources that make it independent of the platform.

5. Loosely Coupled

The loose coupling concept in SOA is inspired by the object-oriented design paradigm that reduces coupling between classes to cherish an environment where classes can be changed without breaking the existing relationship. SOA highly encourages the development of independent services to enhance the efficiency of the software application.

6. Re-usability

An application based on SOA is developed by accumulating small, self-contained and loosely coupled functionality services. It allows the re-usability of the services in multiple applications independently without interacting with other services.

7. Agility

Instead of rewriting and reintegrating each new development project, developers are able to build applications from reusable components or services, increasing SOA’s agility as a result of the ability to quickly respond to new business requirements.

8. Easy Maintenance

The above process should give you a good idea of how to implement a Service Oriented Architecture in iOS Swift. Service Oriented Architectures handle business processes easily and make software code more reusable and bug-free.

Conclusion:

Service Oriented Architecture handles the business process easily and makes the software codes clean, reusable and bug free.  SOA implementation in iOS Swift is interesting. I hope the above process must help you to get a clear picture of implementation.

At Andolasoft we have a team dedicated iOS app developer who has long expertise in implementation of SOA. Our developers can help you in all your mobile app development issues. So don’t hesitate to communicate with them. Book a free consultation to access them directly.

How to Boost Performance Of Your Rails App Using DynamoDB And Memcached

With the increasing number of apps going live on the web, it’s becoming common to see that they use multiple servers. This is mainly due to scalability and availability purposes. But, these types of applications are also often not as responsive as they should be. Using a simple gem called DynamoDB and Memcached will allow you to achieve higher performance in your Rails app. Let me explain,

What is Memcached

Memcached is a high performance, free and open source distributed memory caching system used to speeding up dynamic web applications by alleviating database load. Memcached is simple yet powerful. Its simple design promotes quick deployment, ease of development, and solves many problems facing large data caches.

It is used for speeding up dynamic web applications by reducing database load. In other words, every time a database request is made it adds additional load to the server. Memcached reduces that load by storing data objects in dynamic memory (think of it as short-term memory for applications). Memcached stores data based on key-values for small arbitrary strings.

How does Memcached work?

Memcached is comprised of four main components

  1. Client software – Which is given a list of available Memcached servers
  2. A client-based hashing algorithm – Chooses a server based on the “key”
  3. Server software – Stores values and their keys into an internal hash table
  4. LRU – Determines when to throw out old data or reuse memory

Each item is comprised of a key, expiration time, and raw data.

At a high-level Memcached works as follows:

  1. The client requests a piece of data which Memcached checks to see if it is stored in cache.
  2. There are two possible outcomes here:
    1. If the data is stored in cache: return the data from Memcached (no need to check the database).
    2. If the data isn’t stored in cache: query the database, retrieve the data, and subsequently store it in Memcached.
  3. Whenever information is changed or the expiry value of an item has expired, Memcached updates its cache to ensure fresh content is delivered to the client.

A few important points about Memcached architecture include:

  • Data is only sent to one server.
  • Servers don’t share data.
  • Servers keep values in RAM. If RAM runs out the oldest value is discarded.

What is DynamoDB

Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. With DynamoDB, you can create database tables that can store and retrieve any amount of data and serve any level of request traffic. You can scale up or scale down your tables’ throughput capacity without downtime or performance degradation.

DynamoDB is a particularly good fit for the following use cases

  • Applications with large amounts of data and strict latency requirements
  • Server less applications using AWS Lambda
  • Data sets with simple, known access patterns

Installing Memcached

There are a few ways you can install Memcached. Depending on which system you’re using, the method will vary. As outlined on the official Memcached Installation Wiki, installation from a package is simple.

Using Memcached with DynamoDB in Rails

Memcached is a quick in-memory protest reserving framework that can make Rails run much quicker with not very many changes. Memcached will work on any database used in Rails application.

When the table is small and request volume is low this isn’t much of an issue, but as your database and user volume grow, these can impact the performance of your application. In such cases Memcached plays an important role to reduce the database load by caching the request object in memory.

To use Memcached in Rails app, follow the below steps

Install dalli gem

[code language=”css”]gem ‘dalli'[/code]

Add “dalli” gem to your gem file and install it.

 Development/Production file

[code language=”css”]config.cache_store = :dalli_store</em><em> </em><em>config.action_controller.perform_caching = true[/code]

 Add the above lines in your development.rb or production.rb file as per the requirement

Add Memcached in your method

[code language=”css”]search_query = "user_id = :user_id AND is_approved = :is_approved"
search_param = {":user_id" =&gt; params[:user_id], ":is_approved" =&gt; ‘t’}
all_games = Rails.cache.fetch(‘all_lists’, expires_in: 2.minutes)
{
do_scan(Article.table_name,search_query,search_param)
}[/code]

The above query syntax is an example of combination of Memcached and DynamoDB. In this example once the query executed and the result will store in the “all_list” key of the Memcached and expire after 2 minutes automatically.

Conclusion:

DynamoDB and Memcached is a powerful combination for your Rails app. If you’re looking to improve the performance of your Rails application, this may be the solution for you.

DynamoDB and Memcached involves storing information in an external database, which can be retrieved with a single call. This will allow you to avoid the constant querying of data from your application’s memory.

There are many benefits to this gem, but most importantly, increased response time for your application. Faster response times mean less downtime and more satisfied customers.

You have rails application but don’t know how to maximize the performance with DynamoDB and Memcached. Andolasoft has experienced rails developer who has good hands on DynamoDB and Memcached. So fell free to discuss about your project. Book a free consultation