jack volten
jack volten

Reputation: 273

How can I handle asynchronous data in an alert?

When the NicknameButton button is pressed, the confirmname function is executed, then the createTwoButtonAlert function is executed, and I want to render nicknameError and nicknamesuccess, which are data received through useSelector, to the alert.

However, the nicknamesuccess and nicknameError data were fetched too late, resulting in null. How can I solve this?

this is my code

    const Nickname = () => {
      const {nicknameError, nicknamesuccess} = useSelector((state) => state?.user);

      const createTwoButtonAlert = () =>
        Alert.alert('중복확인', `${nicknameError}` || `${nicknamesuccess}`, [
          {text: 'OK', onPress: () => console.log('OK Pressed'), style: 'OK'},
        ]);


        const confirmname = useCallback(() => {
          setCheck(true),
            dispatch({
              type: CONFIRM_NICKNAME_REQUEST,
              data: {nick},
            }),
            createTwoButtonAlert();
        }, [nick]);

      return (
        <Container>
          <NicknameContainer>
            <Inputs placeholder="닉네임" value={nick} onChange={onChangeNick} />
          </NicknameContainer>

          <NicknameButton onPress={confirmname}>
                <CheckLabel>check</CheckLabel>
              </NicknameButton>

        </Container>
      );
    };

    export default Nickname;

Upvotes: 0

Views: 28

Answers (1)

Kai
Kai

Reputation: 2599

I would recommend adding a useEffect hook, with dependencies of [nicknameError, nicknameSuccess], and triggering the alert there when one of those values becomes non-null.

Upvotes: 1

Related Questions