T
TanStack•4y ago
frail-apricot

How to sync client with server state?

Hey there, I have a Create Post component has a button that opens a sidebar (drawer) that allows me to select the categories (think checkboxes) and I need to reflect the selected categories back to the Create Post component (I'm fetching the categories using react-query). In order to display selected categories back in Create Post component, I'm using Recoil to store the selected categories. However, I'm worried with this approach (or I'm thinking too much). The point is, if a category is deleted, the data won't be in sync (when react-query refetch categories, maybe I can end up with a deleted category in state). In this example, imagine the "categoriesSelected" containing category "typescript", when it shouldn't because it was deleted. In the end, categories component will show all the correct categories, but the create component will show a non-existing category! What is the "best practice" to handle and keep client state in sync when it depends of the server state?
2 Replies
frail-apricot
frail-apricotOP•4y ago
I read this comment here https://github.com/TanStack/query/discussions/1270#discussioncomment-125899 which is seems to be aligned with thoughts. However, I think I'm misunderstanding the suggested approach with my use-case. Any advice @TkDodo 🔮 ? :sadcat:
sunny-green
sunny-green•4y ago
separate client state from server state, then derive the "real" state. if the user has "selected" a category that doesn't exist, the derivation must remove it. something like:
const availableCategories = useQuery(...)
const [selected, setSelected] = useState()

const categories = derive(availableCategories.data, selected)
const availableCategories = useQuery(...)
const [selected, setSelected] = useState()

const categories = derive(availableCategories.data, selected)
derive is what you need to implement / where things are happening

Did you find this page helpful?