Linh Quang Nguyễn
Linh Quang Nguyễn

Reputation: 21

Slate: push to database and show in web

How can I push the content of an editor using slate.js to database and how can I get that content so it will appear on my web page?

Upvotes: 2

Views: 1844

Answers (1)

ZiiMakc
ZiiMakc

Reputation: 36836

You should check this docs: https://docs.slatejs.org/walkthroughs/saving-to-a-database

import { Editor } from 'slate-react'
import Plain from 'slate-plain-serializer'
​
const existingValue = localStorage.getItem('content')
const initialValue = Plain.deserialize(
  existingValue || 'A string of plain text.'
)
​
class App extends React.Component {
  state = {
    value: initialValue,
  }
​
  onChange = ({ value }) => {
    if (value.document != this.state.value.document) {
      const content = Plain.serialize(value)

      //HERE YOU SAVE TO DB
    }
​
    this.setState({ value })
  }
​
  render() {
    return <Editor value={this.state.value} onChange={this.onChange} />
  }
}

//HERE YOU SAVE TO DB I save it like that:

let res = await fetch('/save', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    data: content
  })
})

Upvotes: 1

Related Questions