Skip to content

Suggestion: Recipe for auto save using RTK Query #2890

@einarq

Description

@einarq

I'm trying to replace some custom loading and saving logic in my app with RTKQ.
This app is using auto-save, and its currently storing form state in redux (not recommended I know, but works fine for us in this case, and would be problematic to refactor right now).

The main issue I'm facing now is related to invalidation. When the user makes some changes, the form should automatically save after 1.5 seconds. And the save endpoint is set up to invalidate the query endpoint, so that a new fresh copy is retrieved whenever save finishes. But the user might still be making changes while save is happening, which results in lost changes once the new copy comes back due to the invalidation.
I'm wondering what the recommended approach is for this type of scenario?

Some thoughts:

  1. Could remove the automatic invalidation of the query when the mutation happens, and trigger it manually at a later point instead. A bit risky perhaps, but possible.
  2. Lock the form while the save happens. Not great UX.
  3. Set "skip" to true when there are changes in the form. Tried a bit but didnt behave as expected. Seems setting skip to true always gave me undefined data from the query? Might have to read up more on that one, but abandoned the approach for now anyway.

Probably leaning towards option 1, but looking for some guidance here since it would obviously be better to leave the automatic invalidation in place.

Any thoughts on this? Perhaps there should be a recipe in the docs for this?

I found an npm package for a custom hook with React Query for this, with an option to merge the incoming data with the form data (if I read it correctly).
https://github.com/lukesmurray/react-query-autosync

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions