0

I want to update my callback function:

const getSchema = React.useCallback(
        () => {
            const schema = twSchema(
                labels,
                isInitialWarehouseActive ? initialWarehouse.id : undefined,
                operationTypeDisabled ? initialWarehouse.operation_type : undefined
            );
            schema.addValidator((model, _schema) => {
                if (model.dateRangeMode && (!model.timeRangeMode || model.hasRampHours) && !model.dateInpu.to) {
                    _schema.setModelError('dateInput.to', labels.fieldIsRequired);
              ...
              ...
            });
            return schema;
        },
        [initialStore]
    );

where twSchema:

const twSchema = (labels, initialStoreId, storeOperationType) => new Schema({...

And use case of my getSchema:

<Form
                key="time-window-form"
                ctx="time-window-form"
                eventsEmitter={eventsEmitter}
                model={model}
                onError={onError}
                onSubmit={(data) => {
                   ...
                    }).then(() => {
                       ...
                    })
                        .catch(hint => displayMessageAndHighlightValidatedComponent(hint));
                }}
                schema={getSchema()}
            >

I use this value (getSchema) to my form (I have to set schema to my form).

Depending on the error that can occur I'd like to add some validator to my schema BUT I CAN'T:

 const displayMessageAndHighlightValidatedComponent = (hint) => {
        getSchema().addValidator((model, schema) => {
//this code is not executed!!!
            console.log(schema);
            console.log('SCHEMA');
            schema.setModelError('dateInputField', labels.createNextTimeWindow);
        });
        return onFailed();
    };

The question is why? Why I can't update my object/function? I have to remove useCallback to be able to add validator dynamically...

Matley
  • 1,953
  • 4
  • 35
  • 73
  • 1
    If I am understanding correct, every new call to getSchema will generate a new object, right? – Mukarram Ishaq May 16 '21 at 20:27
  • 1
    Try to define every dependencies explicitly instead of just initialStore. Like labels, isInitialWarehouseActive, operationTypeDisabled, initialWarehouse – Mukarram Ishaq May 16 '21 at 20:36
  • Yes you're right - function twSchema() creates new Schema object every time! I thoght that maybe useCallback works in a different way but there is no magic - every time a new object is created:) Thanks:) – Matley May 16 '21 at 22:00
  • 2
    The incentive to using `useCallback` is for performance. It returns the same instance every time, as long as the second parameter's values don't change. Memoization can be finicky if you don't have your conditions set correctly. Just don't use it unless you need the performance benefits (you usually do not) – Andrew May 16 '21 at 22:27

0 Answers0