smerin Posted August 3, 2021 Share Posted August 3, 2021 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 More sharing options...
OSUblake Posted August 3, 2021 Share Posted August 3, 2021 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 2 Link to comment Share on other sites More sharing options...
OSUblake Posted August 3, 2021 Share Posted August 3, 2021 Related reading. Getting setInterval to work in hooks. https://overreacted.io/making-setinterval-declarative-with-react-hooks/ 1 Link to comment Share on other sites More sharing options...
smerin Posted August 3, 2021 Author Share Posted August 3, 2021 @OSUblake thank you so much for this, and for the extra reading - I'll check that out. Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now