Skip to content

Commit bb9ca01

Browse files
committed
fix: use latest onChange method in setCode
1 parent 01f26aa commit bb9ca01

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

src/Common/CodeEditor/CodeEditor.tsx

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,17 @@ function useCodeEditorContext() {
6565
return context
6666
}
6767

68+
/**
69+
* NOTE: once monaco editor mounts it doesn't update it's internal onChange state.
70+
* Since most of the time onChange methods are declared inside the render body of a component
71+
* we should use the latest references of onChange.
72+
* Please see: https://github.com/react-monaco-editor/react-monaco-editor/issues/704
73+
* Thus as a hack we are using this objects reference to call the latest onChange reference
74+
*/
75+
const _onChange = {
76+
onChange: null
77+
}
78+
6879
const CodeEditor: React.FC<CodeEditorInterface> & CodeEditorComposition = React.memo(
6980
({
7081
value,
@@ -100,7 +111,7 @@ const CodeEditor: React.FC<CodeEditorInterface> & CodeEditorComposition = React.
100111
const monacoRef = useRef(null)
101112
const { width, height: windowHeight } = useWindowSize()
102113
const memoisedReducer = React.useCallback(CodeEditorReducer, [])
103-
const [state, dispatch] = useReducer(memoisedReducer, initialState({mode, theme, value, diffView, noParsing}))
114+
const [state, dispatch] = useReducer(memoisedReducer, initialState({ mode, theme, value, diffView, noParsing }))
104115
const [, json, yamlCode, error] = useJsonYaml(state.code, tabSize, state.mode, !state.noParsing)
105116
const [, originalJson, originlaYaml] = useJsonYaml(defaultValue, tabSize, state.mode, !state.noParsing)
106117
monaco.editor.defineTheme(CodeEditorThemesKeys.vsDarkDT, {
@@ -193,11 +204,14 @@ const CodeEditor: React.FC<CodeEditorInterface> & CodeEditorComposition = React.
193204
editorRef.current.layout()
194205
}, [width, windowHeight])
195206

207+
/**
208+
* NOTE: Please see @_onChange variable
209+
*/
210+
_onChange.onChange = onChange
211+
196212
const setCode = (value: string) => {
197213
dispatch({ type: 'setCode', value })
198-
if (onChange) {
199-
onChange(value)
200-
}
214+
_onChange.onChange?.(value)
201215
}
202216

203217
useEffect(() => {

0 commit comments

Comments
 (0)