jquense / yup

Dead simple Object schema validation
MIT License
22.72k stars 925 forks source link

How to use yup react and developer friendly? #2202

Open BennyAlex opened 4 months ago

BennyAlex commented 4 months ago

I have a react app built with react-i18n.

I try to change the yup locale depending on the resolved language:

useEffect(() => {
        if (ready) {
            // set document language
            document.documentElement.lang = i18n.resolvedLanguage;
            setLocale(yupLocales[i18n.resolvedLanguage]);
            console.log('BaseRoute: yup locale set to', yupLocales[i18n.resolvedLanguage]);
            setLangSetup(true);
        }
    }, [ready, i18n.resolvedLanguage, setLangSetup]);

All children will only be rendered if langSetup is true, but still I only see the default error messages.

When changing the locale manually at the top of a component it works fine: yup.setLocale(yupLocales.de);

How do that automatically affecting all components?

BennyAlex commented 4 months ago

I think the problem is that the schema is defined at the top of the file but not inside the react comonent.

I could move it in there, but then the schema gets recreated every time the component rerenders.

I could also use it with useMemo, but then I have to always import the resolved language to include it in the dependency array, even if it is not required by the component. Also useMemo comes with a cost.

The other aproach of using t('passwordRequired') for every validation is quite tedious and since yup support dynamic fields in the error message there is no need to set a translation string for every field.

So whats the best aproach for this case? Best would be having dynamic locales (by opt-in) I guess.

BennyAlex commented 4 months ago

@jquense Could we have setLocale behave that it will (optionally) reinstanciate the messages?

In my opinion this is the resonable and expected behavior, if you change the language you normally do not want only some parts of your app to be translated.