Bnd10706
Bnd10706

Reputation: 2363

React Native, running an Alert on Startup of App

Building an internal company app, I need to ask a question before the app renders to determine fields.

I have this code.

 useEffect(() => {
    if (startup) {
      console.log('Display Alert');
      {
        createTwoButtonAlert;
      }
    }
  }, []);

For my useEffect, then here is my alert

const createTwoButtonAlert = () =>
    Alert.alert('Title', 'Here is my Question?', [
      {
        text: 'Yes',
        onPress: () => {
          setQuestion(false), setStartup(false);
        },
      },
      {
        text: 'No',
        onPress: () => {
          setQuestion(true), setStartup(false);
        },
      },
    ]);

This alert is not displaying on startup with the current code.

Upvotes: 1

Views: 782

Answers (2)

Bnd10706
Bnd10706

Reputation: 2363

Ok, while Grabriel's response did work. This was one of those stupid mistakes.

I forgot to inclose my alert in {}

a simple fix.

const createTwoButtonAlert = () => {
    Alert.alert('Title', 'Here is my Question?', [
      {
        text: 'Yes',
        onPress: () => {
          setQuestion(false), setStartup(false);
        },
      },
      {
        text: 'No',
        onPress: () => {
          setQuestion(true), setStartup(false);
        },
      },
    ]);
}

Upvotes: 1

Gabriel Lupu
Gabriel Lupu

Reputation: 1447

Try putting the alert code directly inside useEffect inside the root (App) component. It will run only once when the component mounts.

useEffect(() => {
  Alert.alert('Title', 'Here is my Question?', [{
      text: 'Yes',
      onPress: () => {
        setQuestion(false), setStartup(false);
      },
    },
    {
      text: 'No',
      onPress: () => {
        setQuestion(true), setStartup(false);
      },
    },
  ]);
}, [])

Upvotes: 1

Related Questions