Search code examples
javascriptasynchronousreact-nativeimportasyncstorage

How use import async function?


I made a Storage.js file with some Utils function. In most case, I use it in this way:

async someFunction()=>{ let foo = await getOnDevice(someName)}

But the in my case, I have a problem with the syntax

import {AsyncStorage} from 'react-native'

export const saveOnDevice = async (name, data) => {
	try {
		if (data !== null && data !== undefined) {
			await  AsyncStorage.setItem(name, JSON.stringify(data));
		}
	} catch (error) {
		console.log(error)
	}
};

export const getOnDevice = async (name) => {
	try {
		const data = await AsyncStorage.getItem(name);
		if (data !== null && data !== undefined) {
			return data
		}
	} catch (error) {
		console.log(error)
	}
};

How can I use it without declaring an async function?

import {saveOnDevice} from '../../utils/Storage'
export  function fetchUrlWithRedux(url) {
	return (dispatch) => {
		dispatch(fetchUrlRequest(url));
		return fetchUrl(url, dispatch).then(([response, json]) => {
			if (response.status === 200) {
				saveOnDevice('url', json.data.host);
				dispatch(fetchUrlSuccess(json))
			}
			else {
				dispatch(fetchUrlError())
			}
		}).catch(() => dispatch(fetchUrlError()))
	}
}

What is wrong with my code?


Solution

  • If you don't want to use async/await in your main file then you can use promise, like below.

    saveOnDevice('url', json.data.host).then(() => {
      dispatch(fetchUrlSuccess(json))
    })