简体   繁体   中英

How to wait for user action in separate Modal before continuing function execution?

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.

I'm not sure how to implement that.

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 state
const handleActionCalled = async (action: string) => {
    setActionCalled(action);
}

return (
      <View>
        <ReminderModal
          showModal={showReminder}
          handleActionCalled={handleActionCalled}
        />
      </View>

Seems you are overcomplicating the issue, you should break down your flow in multiple steps:

  1. Should be the end of this function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM