REACT NATIVE APP DEVELOPMENT

Let's say on Screen A I have a button. I want to be able to press that button and get an Alert onto Screen B.

On this Screen B, I want the Alert to be more like a notification where it stays there until the user clicks on the alert/notification to complete a task.

    const taskedClick = () => {
        Alert.alert('I am the ALERT'); //I WANT THIS ALERT TO SHOW ON MY NOTIFICATION SCREEN AS A NOTIFICATION 
    }
return (
        <View> 
             <Button onPress={taskedClick}
             style={styles.leftButton}
             type="solid"
             title={post.leftUser.leftButton}
             />
        </View>

The code above has a working button with a working alert but the alert appears on the screen where the button is visible. This is the home screen. I have a notification screen where I want the alert to notify the user that the button was clicked on.

I am using Stack.Navigator and Stack.Screen for my screen names.

1

There are 1 best solutions below

2
On

This should do it, hope it helps :)

You need a way to keep track of state between screens. This way you know in screen B that in screen A the button was pressed. Do this simply with React's useContext. (https://dmitripavlutin.com/react-context-and-usecontext/)

Make a file called DataLayer.js

import React from "react";
const DataLayerContext = React.createContext();

const DataLayerProvider = (props) => {
  const [showAlertInScreenB, setShowAlertInScreenB] = React.useState(false);
  return (
      <DataLayerContext.Provider value={{
          showAlertInScreenB, setShowAlertInScreenB
       }}
       >
      </DataLayerContext.Provider>
      )
  }

export { DataLayerProvider, DataLayerContext }

Next You need to set the showAlertInScreenB to be true in screen A when the buttons clicked. So do this in screen A.

`

 import { DataLayerContext } from "./DataLayer"; 

 const ScreenA = (props)=>{ 
     const DATA_LAYER = React.useContext(DataLayerContext)
     const taskedClick = () => {
             DATA_LAYER.setShowAlertInScreenB(true);
      }
return (
    <View> 
         <Button onPress={taskedClick}
         style={styles.leftButton}
         type="solid"
         title={post.leftUser.leftButton}
         />
    </View>
  }

`

Last of all whenever you go to screen A you condtionaly show the alert based on the value showAlertInScreenB in the data layer

   import { DataLayerContext } from "./DataLayer";
   const ScreenA = (props)=>{ 
   const DATA_LAYER = React.useContext(DataLayerContext)
   if (DATA_LAYER.showAlertInScreenB===true){
        Alert.alert(
        "Alert Title",
     "My Alert Msg",
       [
       {
      text: "Cancel",
      onPress: () => {DATA_LAYER.setShowAlertInScreenB(false)},
      style: "cancel"
    },
    { text: "OK", onPress: () =>{DATA_LAYER.setShowAlertInScreenB(false) }
  ]
      );
       
    }
   }