React ref not render on first load
React
What is the issue?
When I was working on Tiptap editor, I need to make use of React useRef
Typescript
index
const editorRef = useRef<TiptapEditorRef>(null);
return (
<TiptapEditor
ref={editorRef}
onFocus={() => setInputActive(true)}
onBlur={() => setInputActive(false)}
onUpdate={handleGetTags}
/>
)
On first initial render, I want to fetch data and put it in the editor, which seem to work on development mode, but once I start to build and run, the content didn't load at all.
My first thought is to log the ref to see if it have any value at all, and just as i thought, it did not return
null
. This mean that ref did not load at all on first render. Just as the react document said useRef
returns a ref object with a singlecurrent
property initially set to the initial value you provided.
So the temporary solution is to use a state to store if the page fully load. Then when it fully load it should set the editor content.
Typescript
index
const [shouldUpdate, setShouldUpdate] = useState(true);
useEffect(() => {
if (shouldUpdate) setShouldUpdate(false);
}, [shouldUpdate]);
useEffect(() => {
{...fetchDataLogic...}
editorRef.current?.editor?.commands.setContent(data?.content);
},[shouldUpdate)