wix-incubator / autoviews

A library for building user interfaces with JSON schemas, react components and data
MIT License
12 stars 4 forks source link

Render schema validation errors #138

Open Fer0x opened 2 years ago

Fer0x commented 2 years ago

This is copy of internal issue created before autoviews was migrated to external github project

For discussion: If onError callback blocks render then no need to fix different handlers for unmatched schema.

Right now we are ignoring error without onError handler. We still can make use of this callback, but we also can make some run-time decisions when we know that that AutoView in so called "error" state. In order to do this, we need couple of things

  1. Save error in validate method https://github.com/wix-incubator/autoviews/blob/master/packages/core/src/auto-view/auto-view.tsx#L170-L172
    if (!isValid && validate.errors!.length) {
    this.error = formatValidationError(validate.errors![0]);
    if (onError) {
    onError(error)
    }
    }
  2. propagate error to child AutoViews https://github.com/wix-incubator/autoviews/blob/master/packages/core/src/auto-view/auto-view.tsx#L154-L160
    return (
    <AutoViewLogic  
    {...this.props}
    error={this.error}
    schema={subSchema!}
    validation={false}  
    />
    );
  3. Create error component in repository
    
    const repo = new ComponentsRepo();

repo.registerError({ name: 'error-component', predicate: props => { return props.error.schemaPointer === props.schemaPointer }, component: props => ( <> <h2 children={props.data.message} /> <pre style={{backgroundColor: red}} children={JSON.stringify(props.error.data)} /> </> ) })


> 4.  call error component before any logic https://github.com/wix-incubator/autoviews/blob/master/packages/core/src/auto-view/auto-view.tsx#L85
```ts
const error = this.error || this.props.error;
if (error) {
     const ErrorComponent = components.getErrorComponen(this.props);
     if (ErrorComponent) {
          return <ErrorComponent {...this.props} error={error}/>
     }
}

(this will probably require to move validation to constructor and also more complex logic for wrappers)