React beginner here.
My code
import Head from 'next/head';
import styles from '../styles/Home.module.css';
import { useState, useEffect } from 'react';
import Mousetrap from 'mousetrap';
export default function Home() {
const [count, setCount] = useState(0);
const triggerSomething = () => {
console.log(count);
};
useEffect(() => {
Mousetrap.bind(['ctrl+s', 'command+s'], e => {
e.preventDefault();
triggerSomething();
});
return () => {
Mousetrap.unbind(['ctrl+s', 'command+s']);
};
}, []);
return (
<div className={styles.container}>
<main className={styles.main}>
<h1 className={styles.title}>count: {count}</h1>
<p className={styles.description}>
<button onClick={() => setCount(count + 1)}>increment</button>
<br />
<br />
<button onClick={triggerSomething}>triggerSomething</button>
</p>
</main>
</div>
);
}
I'm having an issue when trying to trigger an event from Mousetrap
. The count
variable is not reactive when triggered from mousetrap but reactive when triggered from the button with onClick
.
To replicate this bug you need to:
- click the increment button once
- click the triggerSomething button. The console should print out
1
(the current state ofcount
) - push command+s or ctrl+s to trigger the same method. The console prints out
0
(the state ofcount
when the component loaded). That should print1
(the current state).
What am I doing wrong? What pattern should I use here?
UPDATE: Stackblitz here