5

I want to make patch event from custom component and set a value to another field in document, but couldn’t find documentation about patch events.

there are only example without field specification:

PatchEvent.from(set(value))

Does anybody knows how to specify field name?

This opportunity contains in documentation, but without examples https://www.sanity.io/docs/custom-input-widgets#patch-format-0b8645cc9559

TylerH
  • 20,799
  • 66
  • 75
  • 101

1 Answers1

3

I couldn't get PatchEvent.from to work at all for other fields inside a custom input component but useDocumentOperation combined with withDocument from part:@sanity/form-builder

This is a rough working example using a custom component:

import React from "react";
import FormField from "part:@sanity/components/formfields/default";
import { withDocument } from "part:@sanity/form-builder";
import { useDocumentOperation } from "@sanity/react-hooks";
import PatchEvent, { set, unset } from "part:@sanity/form-builder/patch-event";

// tried .from(value, ["slug"])  and a million variations to upate the slug but to no avail
const createPatchFrom = (value) => {
  return PatchEvent.from(value === "" ? unset() : set(value));
};

const ref = React.createRef();

const RefInput = React.forwardRef((props, ref) => {
  const { onChange, document } = props;
  // drafts. cause an error so remove
  const {patch} = useDocumentOperation(
    document._id.replace("drafts.", ""), document._type)

  const setValue = (value) => {
    patch.execute([{set: {slug: value.toLowerCase().replace(/\s+/g, "-")}}])
    onChange(createPatchFrom(value));
    // OR call patch this way
    patch.execute([{set: {title: value}}])
  };

  return (
    <input
      value={document.title}
      ref={ref}
      onChange={(e) => setValue(e.target.value)}
    />
  );
});

class CustomInput extends React.Component {
  // this._input is called in HOC
  focus = () => {
    ref.current.focus();
  };
  render() {
    const { title } = this.props.type;
    return (
      <FormField label={title}>
        <RefInput ref={ref} {...this.props} />
      </FormField>
    );
  }
}
export default withDocument(CustomInput);
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321