reactjsmonaco-editor

React state change on button click


My calling component,

export const CallingComponent = () => {
  const [getApiData, setApiData] = //initial data binding from api

  return (
    <CustomComponent
      defaultValue={getApiData()}
      onChange={(value: { toString: () => any }) => setApiData(value.toString())
      }
    />
  );

Component which is trying to pass state string to calling component on "Update" button click but its not passing editor content to setApiData state in calling code,

interface CustomComponentProp {
  onChange?: (value: string) => void;
  defaultValue?: string;
}

export const CustomComponent = ({defaultValue,onChange}: CustomComponentProp) => {
  const [value, setValue] = useState("");
  const editorRef = useRef([] as any);
  const [data, setData] = useState(defaultValue);
  const [initialDefault, setInitialDefault] = useState(defaultValue);

  if (initialDefault != defaultValue) {
    setInitialDefault(defaultValue);
    setData(defaultValue);
  }

  const handleEditorDidMount = (editor: any) => {
    editorRef.current = editor;
    editor.focus();
  };

  function handleRemove() {
    setData("");
    setValue("");
  }

  const handleUpdate = () => {
    if (editorRef.current) {
      const content = editorRef.current.getValue();
      setData(content);
    }
  };

  return (
    <Settings>
      <SettingsSection>
        <Editor
          theme="vs-light"
          language="scss"
          value={data}
          onMount={handleEditorDidMount}
          onChange={(value) => setValue(value as string)}
        />
          <Button variant="outline" onPress={handleUpdate}>
            Update
          </Button>
          <Button variant="outline" onPress={handleRemove}>
            Remove
          </Button>
      </SettingsSection>
    </Settings>
  );
};

What I am looking to update setApiData state when Update button is clicked.


Solution

  • Have you tried using onChange inside the handleUpdate()

        if (editorRef.current) {
          const content = editorRef.current.getValue();
          setData(content);
          if (onChange) onChange(content); // Call the onChange with the updated content
        }
      };
    

    When the "Update" button is clicked, the content of the editor is fetched using editorRef.current.getValue() and stored in data. If the onChange prop is provided, it should be called with the new content. Try this and let me know if it works.