final-form / react-final-form

🏁 High performance subscription-based form state management for React
https://final-form.org/react
MIT License
7.39k stars 481 forks source link

React final-form with Select when list change #550

Open quocvan1311 opened 5 years ago

quocvan1311 commented 5 years ago

Is there anyway to reset the value of Field Select when the list of select has changed. For example: I have a Field with Select component and the data list of select is [1, 2, 3, 4] then I pick item "3". Form value with that field has been assign with "3" value. Then the data list has changed to [1, 2, 4, 5, 6] without 3 value. But the form value with that field still keep "3" value in the previous selection. I think when the list change, if the value does not appear anymore on the new list then it should be cleared.

abrad45 commented 4 years ago

I don't think this is something the plugin will ever handle natively, but you can easily handle it yourself in your component. For instance, if you had

<Field component={YourSelect} list={dataList} />

...then inside YourSelect you'd want to do something like

const YourSelect = ({ input, meta, dataList }) => {
    // ...
    const { change } = useForm();
    const yourDefaultOpt = '';
    const { value, name } = input;
    const resetValue = () => change(name, yourDefaultOpt);

    useEffect(() => {
        if (!dataList.includes(value)) {
            resetValue();
        }
    }, [dataList, value])
}

I didn't test this code. there may be some bugs in it. Regardless, it may set you on the right path and, I think, highlights the power of this plugin, which is that doing things like what you describe is no so hard with what you're given out of the box :)