Calling function from bound function always gives me the same value?

103 Views Asked by At

I'm sure there's a really simple solution to this, but I can't figure it out.

 import Mousetrap from 'mousetrap';
 const Slider = ({ children }) => {
  const [activeSlide, setActiveSlide] = useState(0);

  useEffect(() => {
    console.log('mounted');

    const element = document.querySelector('#trap');
    let trap = new Mousetrap(element);

    trap.bind('left', () => {
      test();
    });
  }, []);

  const test = () => {
    console.log(activeSlide + 1);
  };
}

No matter what slide I am on, whenever I call trap.bind('left', ... it thinks I am on slide number 0 and want to go to slide number 1. I guess it checks the value of activeSlide at build time, and then keeps that value, so it doesn't get updated since my function is bound? How can I make sure it always knows the currently active slide?

0

There are 0 best solutions below