Custom Widget in netlify cms that validates with an external API

Disclaimer: I am a backend dev normally using Go / C++ so Im sure I have some major blind spots when it comes to react.

I’m trying to create a custom widget that validates form values with an external API. I’ve created a very simple custom widget that should fetch() to my API when isValid() is called by the cms application. I’m following the documentation here: https://www.netlifycms.org/docs/custom-widgets/#advanced-field-validation.

I have tried doing something simple like:

import React from 'react';

class MyWidget extends React.Component {
  constructor(props) {
    super(props)
    this.state.path = 'http://path/'
    this.state.promise = this.getData()
  };

  getData = () => {
    return fetch(this.state.path, { 
      method: 'GET', 
      headers: {
        'Content-Type': 'text/plain',
      }
    })
  }

  isValid = () => {
    return this.state.promise
  }

  render() {
    return (
      <div></div>
    );
  }
}

export default Widget

But I’m just not sure when I am going to get the chance to recieve the response and decide if the form is valid or not. Any ideas on how Id go about doing that?

What I really want to do is make the request to my server, get the data, decide if it’s ok, then pass the validation. So how can I do that if isValid() needs to return a promise that I cant ever validate?

cheers!

Hi @vimproved,

I think it depends on what you are validating. If you are validating a form, you could call the isValid() method and submit the data based on the value of isValid(). Or, if you want to validate as you type, you may want to do an ‘onChange’ handler with some debounce so your API doesn’t accidentally get DoS-d. :sweat_smile:. Let me know if that helps.

1 Like