Jump to content
Search Community

Accessing current React state when Draggable's onDragEnd fires

smerin test
Moderator Tag

Recommended Posts

I'm having problems accessing the current value of a property held in (React) state when an onDragEnd event fires. The Draggable instance is initiated on component mount and the value of the state property onDragEnd is fixed at whatever it was when the Draggable instance was created.

Here is a simple (and very contrived) example of the issue:
https://codesandbox.io/s/nifty-cori-d2pgt?file=/src/App.js

Apologies if this is simply a React / plain javascript issue, but I though I would ask here first. Thanks!

Link to comment
Share on other sites

Hi smerin!

 

Your value is stale. Here's a hook that can help you out.

 

function useStateRef(defaultValue) {
  const [state, setState] = useState(defaultValue);
  const ref = useRef(state);

  const dispatch = useCallback((value) => {
    ref.current = typeof value === "function" ? value(ref.current) : value;
    setState(ref.current);
  }, []);

  return [state, dispatch, ref];
}

 

Use it just like useState, but it will also give a ref to the current value for use in callbacks.

const [value, setValue, valueRef] = useStateRef(currentValue);
  const [result, setResult] = useState("[result goes here]");
  const box = useRef();

  useEffect(() => {
    Draggable.create(box.current, {
      type: "x, y",
      onDragEnd() {
        setResult(`Value after drag: ${valueRef.current}`);
      }
    });
  }, []);

 

https://codesandbox.io/s/nice-pascal-xtlsw?file=/src/App.js

 

  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...