I have a very simple react app with typescript.
import React, { useState, useMemo } from "react";
import { Editor as Draft, EditorState } from "draft-js";
const Editor: React.FC = () => {
const [editorState, setEditorState] = useState<() => EditorState>(() =>
EditorState.createEmpty()
);
const handleEditorChange = useMemo(
(nextEditorState: EditorState) => setEditorState(nextEditorState),
[editorState]
);
return (
<div>
<Draft editorState={editorState} onChange={handleEditorChange} />
</div>
);
};
export default Editor;
I'm trying to get it to work using useMemo()
but when I wrap handleEditorChange
in useMemo
I get the following error:
argument of type '(nextEditorState: EditorState) => void' is not assignable to parameter of type '() => void'
How to correctly use TypeScript here and get rid of the error?
Typescript requires that useMemo
has an explicit return
.
export function useHello(): string {
return useMemo<string>(() => {
return 'hello';
}, []);
}
useMemo is used to memoize the return value of the function provided to it but you are using it as an onChange handler.
So remove it and just use the function as the handler
const handleEditorChange = (nextEditorState: EditorState) =>
setEditorState(nextEditorState)
Second, you type your state as a function that returns the EditorState
which is not correct, you want the type to be EditorState
.
TypeScript can also infer the type so you don't even need to type it
const [editorState, setEditorState] = useState(EditorState.createEmpty())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With