question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

submitting edit form creates fields with empty string ("") value in a record instead of keeping them uninitialized

See original GitHub issue

What you were expecting: I have SimpleForm form with a <TextInput source="subtitle" /> but subtitle does not exist in fetched data. When a user saves the form without changing the “subtitle” I expect this field to be empty or undefined because the user did not modify it.

What happened instead: When the form is submitted the data field “subtitle” gets an empty string (“”) value. This breaks the integrity of our data because its field is not supposed to be assigned in this way. In the previous version (v3) of react-admin the field was not created if it is not explicitly filled by a user

Steps to reproduce: original data loaded to form:

{
  "userId": 1,
  "id": 3,
  "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
  "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
}

The data after submit(pay attention to “subtitle” field added:

{
  "userId": 1,
  "id": 3,
  "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
  "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis \nmolestiae porro eius odio et labore et velit aut",
  "subtitle": ""
}

Related code: the code of the form below. This is actually from react-admin tutorial

export const PostEdit = props => (
    <Edit mutationMode="pessimistic">
        <SimpleForm>
            <TextInput disabled source="id" />
            <ReferenceInput source="userId" reference="users">
                <SelectInput optionText="name" />
            </ReferenceInput>
            <TextInput source="title" />
            <TextInput source="subtitle" />
            <TextInput multiline source="body" />
        </SimpleForm>
    </Edit>
);
  • CodeSandbox:

Other information: Using parse method to convert empty strings to undefined does not help because empty string value (“”) is also a valid value for some fields. I tried to implement detection of dirty fields using a combination of useFormState and transform callback but it seems strange that this functionality is not supported out of the box

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:2
  • Comments:10 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
pablos44commented, Sep 9, 2022

Probably there was misunderstanding of the prolem. We for instance work with mongodb which doesnt have fixed data scheme. Some values (randomly) are simply not fetched to the form. So I expected react admin to handle correctly the case when those fields stay untouched on save. So they should not be written back to DB. Unfortunatelly because the way react-hook-form was integrated it became impossible in v4.
To overcome this problem it is not suficcient to parse values you also need to rack which values are untouched (not dirty). Unfortunatelly the transform of the Edit does not have an access to the Form state (cant use useFormState), so this context need somehow to be transfered from inside the form to the ancestor Edit conrol.
I made some quick and dirty solution , but I believe it can be made in much more ellegant way inside reacr-admin edit or other related contexts

const SafeEditForm = ({ children }: { children: ReactNode }) => {
   
    const dirtyFields = useRef({});
    
    const handleTransform: TransformData = (data, options: any) => {
        const { previousData } = options;
        const updates = filter(dirtyFields.current, data);
        const final = merge({ ...previousData }, updates);
        return final;
    }

    const WrapChildren = useCallback(() => {
        const { dirtyFields: dirty } = useFormState();
        dirtyFields.current = dirty;
        return <>{children}</>
    }, [children])


    return (
        <Edit transform={handleTransform}>
            <Form>
                .....

            </Form>
        </Edit>
    )
}


I hope to see it reflected in some future version of ra

2reactions
slax57commented, Sep 8, 2022

Hi guys, Sorry I took so long to answer.

So indeed, this is actually a breaking change from v3 to v4, due to the change of the forms library. As explained here, react-hook-form does not handle undefined values (because it uses uncontrolled inputs by default).

native input will not return undefined, and this library doesn’t support undefined as well

Native web inputs don’t return undefined, only empty strings in case of an empty value.

This is what is implemented in react-admin.

If you need to workaround this, you can use the parse prop on a per-input basis, or the transform prop on the <Create>, <Edit>, or <SaveButton> components. See the docs here: https://marmelab.com/react-admin/Upgrade.html#sanitizeemptyvalues-has-been-removed

Since we do not plan to change this, I’m going to close this issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

" No Data to Display" in edit form - Power Platform Community
Solved: Hi, I am trying to create a Edit form for the users to Subscribe in an event. The form looks fine when...
Read more >
Non-nullable property must contain a non-null value when ...
The compiler is warning you that the default assignment of your string property (which is null) doesn't match ...
Read more >
Use empty string, null or remove empty property in API ...
Empty string still is a value, it is just empty. ... set and left empty, I prefer to keep them in the response...
Read more >
How can I prevent empty strings being used to bypa...
I have UI Policies that set fields as Mandatory. ... a space for a required field on the Change form and then advancing...
Read more >
Database fields are polluted with both nil and empty ...
When a user submits a form and leaves certain fields blank, they get saved as empty '' strings in the DB. If the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found