0
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.

RDK
  • 67
  • 1
  • 7
  • You can use [this](https://stackoverflow.com/questions/34687091/can-i-execute-a-function-after-setstate-is-finished-updating) syntax. – Vector-Hector Oct 30 '21 at 23:14

1 Answers1

0

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.

Arjun
  • 376
  • 3
  • 13