I have an React App using React Query to load a dataset of folders containing items. The app allows the user to drag/sort items (within a folder and drag to another folder). Before implementing drag/sort it was simple, RQ fetched the dataset folderData and then the parent supplied data to child components: parent > folder > item .
In order to implement drag/sort, I am now having to copy the entire dataset folderData into a client-state variable foldersLocal. This is the only way I could figure out how to change the UI when the user moves an item.
However, I feel like this approach essentially removes most of the benefits of using React Query because as soon as the data is fetched, I copy the entire dataset into a "client-side" state variable (foldersLocal) and only work with it. This also makes the QueryClientProvider functionality effectively useless.
Is there a better way to approach this? Or am I missing something?
// Fetch data using React Query
const {isLoading, isError, foldersData, error, status} = useQuery(['folders', id], () => fetchFoldersWithItems(id));
// Place to hold client-state so I can modify the UI when user starts to drag/sort items
const [foldersLocal, setFoldersLocal] = useState(null);
// Store React Query data in client-state everytime it's fetched
useEffect(() => {
if (status === 'success') {
setFoldersLocal(foldersData);
}
}, [foldersData]);
// Callback to change "foldersLocal" when user is dragging an item
const moveItem = useCallback((itemId, dragIndex, hoverIndex, targetFolderId) => {
setFoldersLocal((prevData) => {
// change data, etc. so the UI changes
}
}
// Drastically simplified render method
return (
<QueryClientProvider client={queryClient}>
<FolderContainer folders={foldersLocal} moveItem={moveItem} moveItemCompleted={moveItemCompleted}/>
</QueryClientProvider>
)