How do get value from async function without then() - react-native

I know I have to use then() or in a async function to use await to get the value from other async function .
but how to I get value directly ?
I try to pass the value in normal function but not work .
there is no other way to get the value directly ?
thanks
here is ample :
load_data_normal(key){
this.load_data(key).then((ret_val)=>{
console.log(ret_val);
return ret_val;
})
}
load_data = async (key) => {
const MMM = await AsyncStorage.getItem(key);
return MMM;
}
load_data function just work with then(), but load_data_normal not work ,
I just want to get value from get_data without then ..

The simple solution is just adding async to your load_data_normal, if you want to know more read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
load_data_normal = async (key) => {
const ret_val = await this.load_data(key);
return ret_val;
}
load_data = async (key) => {
const MMM = await AsyncStorage.getItem(key);
return MMM;
}

Normal function doesn't work with await. You need an async function.
const asynFunction = async() => {
const results = await fetch(url);
console.log('results', results)
}
If you don't want to use async, you need to create a new promise.
const load_data_normal = (key) => {
localStorage.setItem("abc", "somevalue in abc");
load_data(key).then((resuls) => {
console.log("abc", resuls);
});
};
const load_data = (someKey) => {
return new Promise((resolve) => resolve(localStorage.getItem(someKey)));
};
load_data_normal("abc");
Sandbox

Related

A call to an async function is not awaited. Use the "await" keyword in Test Cafe

I'm getting this error:
A call to an async function is not awaited. Use the "await" keyword
before actions, assertions or chains of them to ensure that they run
in the right sequence.
But I am using an await within my code, what am I doing incorrectly?
test("Accepts the cookie", async t => {
const interfaceSelect = Selector('#sp_message_iframe_617100');
await
t.switchToIframe('#sp_message_iframe_617100')
t.click(Selector('button').withText('Accept'))
t.switchToIframe('#select_region-select-module_select_30IZf')
const countrySelect = Selector('#region-select-module_select__30lZf');
t.click(Selector('button').withText('United Kingdom'))
});
Thanks,
The TestCafe's methods are chainable and return a Promise.
You need to add an await before each method call or one await before the whole chain.
test("Accepts the cookie", async t => {
const interfaceSelect = Selector('#sp_message_iframe_617100');
await t.switchToIframe('#sp_message_iframe_617100');
await t.click(Selector('button').withText('Accept'));
await t.switchToIframe('#select_region-select-module_select_30IZf');
const countrySelect = Selector('#region-select-module_select__30lZf');
await t.click(Selector('button').withText('United Kingdom'));
});
test("Accepts the cookie", async t => {
const interfaceSelect = Selector('#sp_message_iframe_617100');
await t
.switchToIframe('#sp_message_iframe_617100')
.click(Selector('button').withText('Accept'))
.switchToIframe('#select_region-select-module_select_30IZf');
const countrySelect = Selector('#region-select-module_select__30lZf');
await t.click(Selector('button').withText('United Kingdom'));
});

Jest does not continue after async method

I have an async method triggered by a click event where I make a call to an API and then process the response, like this:
async confirmName () {
const {name, description} = this.form;
const [data, error] = await Pipelines.createPipeline({name, description});
if (error) {
console.error(error);
this.serviceError = true;
return false;
}
this.idPipelineCreated = data.pipeline_id;
return true;
}
The test looks like this:
test("API success", async () => {
const ConfirmNameBtn = wrapper.find(".form__submit-name");
await ConfirmNameBtn.vm.$emit("click");
const pipelinesApi = new Pipelines();
jest.spyOn(pipelinesApi, "createPipeline").mockResolvedValue({pipeline_id: 100});
const {name, description} = wrapper.vm.form;
pipelinesApi.createPipeline().then(data => {
expect(wrapper.vm.pipelineNameServiceError).toBe(false);
wrapper.setData({
idPipelineCreated: data.pipeline_id
});
expect(wrapper.vm.idPipelineCreated).toBe(data.pipeline_id)
}).catch(() => {})
})
A basic class mock:
export default class Pipelines {
constructor () {}
createPipeline () {}
}
I'm testing a success API call and I mock the API call returning a resolved promised. The problem is the coverage only covers the first two lines of the method, not the part where I assign the response of the API call. Is this the correct approach?
Edit:
Screenshot of coverage report:
Don't mix up await and then/catch. Prefer using await unless you have very special cases (see this answer):
test("API success", async () => {
const ConfirmNameBtn = wrapper.find(".form__submit-name");
await ConfirmNameBtn.vm.$emit("click");
const pipelinesApi = new Pipelines();
jest.spyOn(pipelinesApi, "createPipeline").mockResolvedValue({pipeline_id: 100});
const {name, description} = wrapper.vm.form;
const data = await pipelinesApi.createPipeline();
expect(wrapper.vm.pipelineNameServiceError).toBe(false);
wrapper.setData({
idPipelineCreated: data.pipeline_id
});
expect(wrapper.vm.idPipelineCreated).toBe(data.pipeline_id)
expect(wrapper.vm.serviceError).toBe(false);
})

Setting state using hooks resulting in null value in subsequent function call

First I call this where result is an object
const _onSaveEvent = async (result) => {
console.log(result);
setSignature(result);
followUp();
};
Then I invoke,
const handleActualSubmission = async () => {
console.log(signature);
const { encoded, pathName } = signature;
const extension = pathName.split('.').pop();
const path = `${RNFS.DocumentDirectoryPath}/${uuidv4()}.${extension}`;
await RNFS.writeFile(path, encoded, 'base64');
stops.forEach(async (stopForPhotoConf) => {
await saveDeliveryProof(driverRoute, stopForPhotoConf, path, extension, 'signature');
});
close();
};
The resulting error is signature being null on line 1 of handleActualSubmission where const [signature, setSignature] = useState(null);
I have verifeid that the _onSaveEvent function always returns a truthy value. This issue does not appear every time this sequence of functions runs.
This code should work:
useEffect(() => {
if (signature) {
processSavedSignature();
}
}, [signature]);

Reusing async function in react native

I am building a page to fetch data from API when loaded, but encounter waring an effect function must not return anything besides a function which is used for clean-up when trying to reuse the function for fetching data
const dispatch = useDispatch();
useEffect(() => {
// this way does not work as I expected, my page does not show data I fetched
const getData = async () => {
const result = await dispatch(actions.getList());
setState(result);
};
getData();
},[isFirstLoaded]);
But I get the warning when trying below
const dispatch = useDispatch();
const getData = async () => {
const result = await dispatch(actions.getList());
setState(result);
};
useEffect(async() => {
// this way gives me the data but with a warning
await getData();
},[isFirstLoaded]);
How should I reuse the getData function? I did not update the state if I am not using the async and await here. When I use async and await here, I get the warning. Thanks.
overall, you are heading in the right direction. For fetching data, you'd wanna use use Effect and pass [] as a second argument to make sure it fires only on initial mount.
I believe you could benefit from decoupling fetching function and making it more generic, as such:
const fetchJson = async (url) => {
const response = await fetch(url);
return response.json();
};
const Fetch = () => {
const [data, setData] = useState(null);
useEffect(() => {
fetchJson("https://api.coindesk.com/v1/bpi/currentprice.json")
.then(({ disclaimer }) => setData(disclaimer));
}, []);
return <Text>{data}</Text>;
};

React native AsyncStorage bad response

Have created React Native app and ned to use AsyncStorage to benefit from it's storage mechanism.
To save in AsyncStorage use code:
_storeData = async (param) => {
try {
let par = JSON.stringify(param);
//await AsyncStorage.setItem(this.key, par);
Utilities.setItem(this.key, par);
this._retrieveData();
} catch (error) {
console.log(JSON.stringify(error));
}
};
To retrieve data:
_retrieveData = async () => {
try {
const value = Utilities.getItem(this.key);
if (value !== null) {
alert('data is new: ' + JSON.stringify(value));
}
} catch (error) {
}
};
And, to setItem and getItem in Utilities partial:
const setItem = (key, value) => {
if (!key || !value) return;
AsyncStorage.setItem(key, value);
};
const getItem = (key) => {
if (!key) return;
var val = AsyncStorage.getItem(key);
return val;
};
Data is being saved, but response I'm getting does not look correctly, as it's a string of 'weird' characters:
{"_40":0,"_65":0,"_55":null,"_72":null}
Does anybody know why I'm getting such answer?
Note that AsyncStorage.getItem is also async - the weird characters represent the promise being returned by getItem.
Use var val = await AsyncStorage.getItem(key); and mark your getItem utility function as async. You'll need to await on any calls to Utilities.getItem and Utilities.setItem as well.