Reputation: 2661
How can I await, to resolve/reject, the promise returned by a function wrapped in the react hook "useMemo"?
Currently, my code looks like this:
// Get the persisted email/username
const persistedUsername = useMemo(async () => {
let username;
try {
username = await AsyncStorage.getData(`@${ASYNC_STORAGE_KEY}:username`);
} catch {}
return username;
}, []);
What I am trying to achieve is to get the data before the component is rendered, some kind of "componentWillMount" life-cycle. My two options were:
@DennisVash has proposed the solution to this problem in the comments:
Blocking all the visual effects using the useLayoutEffect hook (some kind of componentDidMount/componentDidUpdate) where the code runs immediately after the DOM has been updated, but before the browser has had a chance to "paint" those changes.
As you can see, persistedUsername is still a promise (I am not waiting the result of the asynchronous function)...
Any ideas? Is it not a good idea to perform asynchronous jobs with this hook? Any custom hook?
Also, what are the disadvantages of performing this operation in this way compared to using useEffect and useState?
Same thing with useEffect and useState:
useEffect(() => {
// Get the persisted email/username
(async () => {
const persistedUsername = await AsyncStorage.getData(
`@${ASYNC_STORAGE_KEY}:username`
);
emailOrUsernameInput.current.setText(persistedUsername);
})();
}, []);
Thank you.
Upvotes: 3
Views: 13422
Reputation: 53994
Seems like the question is about how to use componentWillMount
with hooks which is almost equivalent to useLayoutEffect
(since componentWillMount
is deprecated).
For more additional info, you should NOT resolve async
action in useMemo
since you will block the thread (and JS is single-threaded).
Meaning, you will wait until the promise will be resolved, and then it will continue with computing the component.
On other hand, async hooks like useEffect
is a better option since it won't block it.
Upvotes: 6