I'm developing a drink counter app. User can add drinks but also has a drinkLimit state that is used to remind the user if the limit is reached when adding drinks. This reminder pops up in a modal with cancel and continue buttons when drink count has reached it's limit. The user can then either cancel the new drink addition or continue with it.
The problem is that I need to somehow wait or check for the user's action (clicking either "cancel" or "continue" in the modal), and based on that either return out of the addDrink function or continue the addition. I'm not sure how to implement that.
Using async/await
seems intuitive but how can I await for a function when that function runs only after user clicks a button?
Using callbacks might be another solution but there as well I would need to halt the execution until user makes his action.
This seems like a common use case but I still can't seem to find any questions or tuts about this specific case.
App.tsx
const App = () => { const [drinklist, setDrinkList] = useState<DrinkType[]>(); const [favorites, setFavorites] = useState<FavDrinkType[] | null>(null); const [drinkLimit, setDrinkLimit] = useState<number>(); const [actionCalled, setActionCalled] = useState<string | null>();const addDrink = (alcPercent: number, amount: number, name?: string) => { // if drink limit has been reached open reminder modal if (drinkLimit && drinklist) { if (drinklist?.length >= drinkLimit) { // how do I pause the execution here? const action = await openReminder(); //cancel add if (action === 'cancel') { setShowReminder(false); return } } } // continue add setShowReminder(false); // *addition logic* (irrelevant) };// Opens the modal (and waits for the user's action?)const openReminder = async () => { setShowReminder(true); // should I wait for function handleActionCalled()?}// Modal calls this and sets stateconst handleActionCalled = async (action: string) => { setActionCalled(action);}return (<View><ReminderModal showModal={showReminder} handleActionCalled={handleActionCalled} /></View>
ReminderModal.tsx:
const ReminderModal = ({ showModal, handleActionCalled,}: ReminderModalProps) => { const handleAction = (action: string) => { switch (action) { case 'cancel': return handleActionCalled('cancel'); case 'continue': return handleActionCalled('continue'); } }; return (<Modal visible={showModal} animationType="slide" transparent={true}><TouchableOpacity onPress={() => handleAction('cancel')}><View><Text>Cancel</Text></View></TouchableOpacity><TouchableOpacity onPress={() => handleAction('continue')}><View><Text>Continue</Text></View></TouchableOpacity></Modal>