Hello Friends š,
Welcome To Infinitbility! ā¤ļø
This article will help you to use async await in react native, we use async-await to manage time consuming tasks using async await we have the option to wait for the first task before executing the second task. Today we will learn to create async functions and how to use await with example in-class component and functional component.
Letās start today topic how to use async await in react native āļø
Introduction
First, we have to understand when we use async and when await āļø.
Async keyword use for define function for use await task, when you want to use to await for wait task then first you have to define async function. Await keyword use for stop execution till task response, we will use multiple await calls in one async function.
Syntax
After understand the meaning š of async await we have to understand their syntax to use in react native, let start with async.
Async syntax for normal function example
async function exampleOne(items) {
}
Async syntax for arrow function example
const exampleSecond = async () => {
}
Await syntax example
You can use await function native library calls or you can also use for call your async function
await AsyncStorage.setItem("@ProductTour:key", "true");
Await call own function example
const exampleSecond = async () => {
await exampleOne();
}
Async await example in class component
Letās understand how to use and call async await in class component, well first we need class component structure š
import React, { Component } from 'react';
import { Text } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
class ClassComponent extends Component {
constructor(props) {
super(props);
this.state = {
name : "Infinitbility",
}
}
componentDidMount() {
this.doTask();
}
doTask = async () => {
// Some consuming task like fetch api or await calls
await AsyncStorage.setItem("@ProductTour:key", "true");
await this.setState({name : "Infinitbility".toUpperCase() });
}
getName = () => {
return this.state.name;
}
render() {
return (
<Text>Hello, Hear {this.getName()}!</Text>
);
}
}
export default ClassComponent;
Async await example functional component
Letās understand how to use and call async await in functional componentā¦.
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
const FunctionalComponent = () => {
const [isFlag, setIsFlag] = useState(false);
useEffect(() => {
async function changeFlag() {
await delay(1500);
setIsFlag(!isFlag)
}
changeFlag();
}, []);
const delay = async ms => new Promise(res => setTimeout(res, ms));
return (
<View>
{isFlag && <Text>Hello, I am your cat! </Text>}
</View>
);
}
export default FunctionalComponent;
Thanks For Reading…