Kirit Modi Kirit Modi - 2 months ago 16
React JSX Question

Callback function definition and Calling issue in react native



Friend I will take one class for define to all function. Now We required some of the function with its callback. So I define as below.

CallBack define :

export const getStoredData(key: string, callback?: ?(error: ?Error, result: ?string)) =>{
try {
const value = await AsyncStorage.getItem(key);
if (value !== null){
return value
}
} catch (error) {
return error
}
}


Call the function as below :

getStoredData('apple' , (error , result) =>{
if (error) {
console.log('error is = ', error);
} else {
console.log('result is = ', result);
}
});


But i have error to define function unexpected token.

Please help me.

Val Val
Answer Source

As @MayankShukla said, you aren't using arrow function correctly.

To fix your expression, you also need to add =>void as below to fix the function type of callback,

export function getStoredData(key: string, callback?: ?(error: ?Error, result: ?string) => void ) {

In my vs code Unexpected Identifier disappeared with above code.

Edited for comment 1: for getting result from callback, try change the function

export async function getStoredData(key: string, callback?: ?(error: ?Error, result: ?string) => void ) {
    try {
        const value = await AsyncStorage.getItem(key);
        if (value !== null) {
            callback(null, value);
            return value;
        }
    } catch (error) {
        callback(error, null);
        return error;
    }
}