lukasbach / react-complex-tree

Unopinionated Accessible Tree Component with Multi-Select and Drag-And-Drop
https://rct.lukasbach.com
MIT License
944 stars 74 forks source link

In "Interaction Modes", I can not control the state inside onclick #242

Closed bcburak closed 1 year ago

bcburak commented 1 year ago

In interaction mode I'm trying to call onclick for each tree item and want to update state however can not.

This example is from your docs page;

`function App() { const [start,setStart] = useState(false); return ( <UncontrolledTreeEnvironment dataProvider={new StaticTreeDataProvider(longTree.items, (item, data) => ({ ...item, data }))} getItemTitle={item => item.data} defaultInteractionMode={{ mode: 'custom', createInteractiveElementProps: (item, treeId, actions, renderFlags) => ({ onClick: e => { setStart(true); console.log(start); actions.focusItem(); }, onFocus: () => { actions.focusItem(); }, tabIndex: !renderFlags.isRenaming ? (renderFlags.isFocused ? 0 : -1) : undefined, }), }} viewState={{

      expandedItems: ['Fruit', 'Meals'],
    },
  }}
>
  <Tree treeId="tree-4" rootItem="root" treeLabel="Tree Example" />
</UncontrolledTreeEnvironment>

); } ` "start" state could be true on console log.

Desktop (please complete the following information):

lukasbach commented 1 year ago

Hi! Looks like you are doing a state update with the set function of a useState hook, and then immediately afterwards reading the get property of the state. Updating the state will schedule a rerender in react, and react will internally only update the value for the next rerender. Btw even then, you need to make sure that the reference to the state variable is not affected by a stale closure. This is a peculiarity of react and not related to this library, and also by design by the react.