Reputation: 33
I'm unable to persist the content of tiptap editor when the page gets re-render. I'm saving the editor's content in json format using react state.
What I want is when the page gets refreshed the editor content should not be erased. Like we use setItem and getItem with localStorage to persist the data, but this does not work for tiptap editor I guess because the content is ini json format. Any idea how I should go about it?
Upvotes: 0
Views: 2169
Reputation: 330
Tiptap has 3 output options:
Here you can find more information in their documentation.
Option 1 - HTML
// src/Tiptap.jsx or // src/Tiptap.tsx
import { useEditor, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
const Tiptap = () => {
const editor = useEditor({
extensions: [
StarterKit,
],
content: window.localStorage.getItem('editor-content'),
onUpdate: ({ editor }) => {
window.localStorage.setItem('editor-content', editor.getHTML())
}
})
return (
<EditorContent editor={editor} />
)
}
export default Tiptap
Option 2 - JSON
// src/Tiptap.jsx or // src/Tiptap.tsx
import { useEditor, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
const Tiptap = () => {
const editor = useEditor({
extensions: [
StarterKit,
],
content: JSON.parse(window.localStorage.getItem('editor-content') || '{}'),
onUpdate: ({ editor }) => {
const jsonContent = JSON.stringify(editor.getJSON());
window.localStorage.setItem('editor-content', jsonContent)
}
})
return (
<EditorContent editor={editor} />
)
}
export default Tiptap
I've tested both options are working.
I hope you find it helpful.
Upvotes: 4