export default function ProjectCard1() {
const [open, setOpen] = React.useState(false);
const handleClick = () => {
setOpen(true).then(response => {
window.open("https://project-uts-teori.vercel.app/");
});
};
const handleClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setOpen(false);
};
it says TypeError: Cannot read properties of undefined (reading 'then'). i need to display the alert message first before it window.open to the site.
CodePudding user response:
When setting a value using the useState hook, it does not return a promise, meaning you can't use the .then
syntax. Instead, you'll need to use the useEffect hook and add open
as a dependency.
export default function ProjectCard1() {
const [open, setOpen] = React.useState(false);
const handleClick = () => {
setOpen(true)
};
React.useEffect(() => {
if (open) {
window.open("https://project-uts-teori.vercel.app/");
}
}, [open])
const handleClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setOpen(false);
};
}
With this, the useEffect function will be called every time the open
variable changes, and it will only redirect the user if the value is true
.