Skip to content

Unexpected conversion of Date to string in optimistic updates in useUpdate and Forms #10478

@kafendt

Description

@kafendt

What you were expecting:
Hey there, first off, thank you very much for all the great work you are doing on react-admin. I very much appreciate it and love what you have built!

I am experiencing problems due to how react-admin handles optimistic updates and just wanted to raise awarness for this.
The problem lies in the code below here:

const clonedData = JSON.parse(JSON.stringify(data));

        // Stringify and parse the data to remove undefined values.
        // If we don't do this, an update with { id: undefined } as payload
        // would remove the id from the record, which no real data provider does.
        const clonedData = JSON.parse(JSON.stringify(data));

I have objects in the form of:

interface Appointment {
  start: Date
  end: Date
}

Now, I have a form which i use to update these appointments which also outputs start and end as javascript Date types.
I was expecting, that optimisic updates based on this would keep the types intact and save an updated object of the same shape into the query cache.

What happened instead:

When react-admin performs its optimisic update and updates the @tanstack/react-query cache, it does it using the code snippet above to strip all undefined values. Unfortunately in the process, through the JSON.stringify, it also transforms my Dates into strings.
So now I have an appointment in the form of:

interface Appointment {
  start: string
  end: string
}

in my cache until the response from the server comes along and places a new object with Dates in it again. Unfortunately in the meantime the date from the optimistic updates, leads to unexpected behaviour if it isn't handled correctly.

My question now is: If the only purpose of the JSON.parse(JSON.stringify(...)) is, to remove undefined values. Wouldn't it make sense to recursively remove undefined values and keep the other types intact? I like having Dates everywhere in my application and do the conversion to string right in the API Layer but this behaviour currently messes with that workflow.

What are your thoughts on this? Is this the desired behaviour or could we improve on it?

Thank your very much!

Environment

  • React-admin version: latest (5.5.2)
  • Last version that did not exhibit the issue (if applicable): -
  • React version: -
  • Browser: -
  • Stack trace (in case of a JS error): -

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels
    No fields configured for Enhancement.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions