Reputation: 223
Hello I have a modal that will pop up when my app detects Apple device, load because the modal open is set to true. But when It's loaded the value of the localstorage will be 1. then if it's 1, I set the open to false so it will not open again when I go back to that component.
This is my code on the component
const MasterIndexPage = () => {
const classes = useStyles()
const [userAgent, setUserAgent] = useState('')
const [isAndroid, setIsAndroid] = useState(false)
const [isApple, setIsApple] = useState(false)
const [isWindows, setIsWindows] = useState(false)
const [open, setOpen] = useState(true)
// setOpen(localStorage.getItem('formModal') == 1)
const handleClose = () => {
setOpen(false)
}
const visible = localStorage.getItem('formModal')
if (!visible) {
localStorage.setItem('formModal', 1)
setOpen(true)
console.log('first load')
}
if (visible) {
// setOpen(false) // when I uncomment this I'm getting an error
console.log('second load')
}
useEffect(() => {
if (navigator.userAgent.match(/Android/i)) {
setIsAndroid(true)
} else if (navigator.userAgent.match(/iPhone|iPod|iPad/i)) {
setIsApple(true)
} else {
return null
}
}, [])
return (
<h1>Hello</h1>
<div>
{isApple ? (
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={`${classes.modal}`}
open={open}
onClose={handleClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500,
}}
>
<div id="popup">
<h4 className="h4_addtohome">Add my App!</h4>
<p className="p__addtohome">
Tap below to add an icon to your home screen for quick access!
</p>
</div>
</Modal>
) : null}
</div>
)
}
export default MasterIndexPage
I'm achieving that if it detects an apple device this will pop up, then if the user close it will not pop up again unless it clears cache
When I'm enabling the setOpen(false) I'm getting this error
Upvotes: 0
Views: 637
Reputation: 5497
You are making the decision based on the visible
flag read from the local storage. So you can make that as a dependency to your useEffect.
const visible = localStorage.getItem("formModal");
useEffect(() => {
if (!visible) {
localStorage.setItem("formModal", 1);
setOpen(true);
console.log("first load");
}
if (visible) {
// setOpen(false) // when I uncomment this I'm getting an error
console.log("second load");
}
}, [visible]);
Upvotes: 2