Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow functions with async and await in react native

I am trying to save data in AsyncStorage in react-native. I want to save it asynchronous so using async and await keyword.

  async onPositiveClickListener = () => {
    // user has completed product tour_end
    try {
      await AsyncStorage.setItem("@ProductTour:key", "true");
      const { navigate } = this.props.navigation;
      navigate("DashboardScreen");
    } catch (error) {
      console.log(error);
    }
  };

I am getting an error while saving program

SyntaxError: Unexpected token, expected ( (40:32)
  38 |   };
  39 | 
> 40 |   async onPositiveClickListener = () => {
     |                                 ^
  41 |     // save user has completed product tour_end
  42 |     try {
  43 |       await AsyncStorage.setItem("@ProductTour:key", "true");
Hide Stack Trace
SyntaxError: Unexpected token, expected ( (40:32)
  38 |   };
  39 | 
> 40 |   async onPositiveClickListener = () => {
     |                                 ^
  41 |     // save user has completed product tour_end
  42 |     try {
like image 840
N Sharma Avatar asked May 01 '17 11:05

N Sharma


People also ask

Can we use async await in arrow function?

Using await in any other case is a syntax error. Notice the use of async keyword at the beginning of the function declaration. In the case of arrow function, async is put after the = sign and before the parentheses. Async functions can also be put on an object as methods, or in class declarations as follows.

How do you use async and await in React Native?

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.

How async functions will work in React Native?

AsyncStorage is a simple, asynchronous, unencrypted by default module that allows you to persist data offline in React Native apps. The persistence of data is done in a key-value storage system. There are numerous scenarios where this module can be beneficial.

Why we should not use arrow functions in React?

An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.


1 Answers

Async named arrow function should be declared like

const onPositiveClickListener = async () => {
    // user has completed product tour_end
    try {
      await AsyncStorage.setItem("@ProductTour:key", "true");
      const { navigate } = this.props.navigation;
      navigate("DashboardScreen");
    } catch (error) {
      console.log(error);
    }
  };
like image 56
Shubham Khatri Avatar answered Oct 11 '22 19:10

Shubham Khatri