I am currently working on a library for react, and don't exactly know how I technically can implement a feature that I have in mind.
Basically its a form validation library and all config goes as a param to the hook. Looks like that:
const myFormReferenceObject = useForm({
onSubmit: (values) => {
// do whatever you want with the values
},
initialState: record,
formatMessage: translate,
submitUnmountedFields: false
});
The thing is, I think it could be very useful to have some kind of global configuration so that you don't have to repeat yourself 100 times for each form you build.
My first idea was to do it like axios, where you create an axios instance and configure the instance globally. Now, I don't have an instance object since I simply call a function/react hook.
Then I had the idea of having a namespace in the window object with the config laying there. Then my hook could always check if there is a config in that window["namespace"] to configure or override all forms at once.
Another, maybe more react way of doing it, would be to create a context for the configuration. But to be honest I really dont want to do it this way, because the library itself is very simple and easy to use. 1. Call hook to create a form, 2. pass the form reference to each input field with field level validator and props etc. I like the simplicity and adding a context kinda destroys the simplicity since you always have to surround your components with a context. On the other hand you could then have multiple contexts for different modules in the application, which would be pretty cool too.
Do you have a better idea or do you think I should just go with the window approach?
If you have global configuration you can just rest spread it when calling useForm.
const myFormReferenceObject = useForm({
...myGlobalConfig,
onSubmit: (values) => {
// do whatever you want with the values
},
});
Also if you use the window approach you can do window[a symbol] instead of window[a string] to avoid conflicts.