user6198643
user6198643

Reputation:

How to save draft-js editorState data to Meteor?

How to save the Data from draft-js to Meteor?

I'm trying to...

Here is Draft.js. Here's a Meteor starter kit. There's also this article which seems relevant.

But I can't apply the bits of information to the project.

Considering my ~/imports/collections/bins.js to be

import { Mongo } from 'meteor/mongo';

Meteor.methods({
  'bins.insert': function() {
    return Bins.insert({
      createdAt: new Date(),
      content: '',
      sharedWith: [],
      ownerId: this.userId
    });
  },

  'bins.remove': function(bin) {
    return Bins.remove(bin);
  },

  'bins.update': function(bin, content) {
    return Bins.update(bin._id, { $set: { content } });
  }
});

export const Bins = new Mongo.Collection('bins');

And considering the guidelines found in A Beginner’s Guide to Draft JS to be

import React from ‘react’;
import {Editor, EditorState, RichUtils} from ‘draft-js’;
export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
  }
  _onBoldClick() {
    this.onChange(RichUtils.toggleInlineStyle(
      this.state.editorState,
      ‘BOLD’
    ));
  }
  render() {
    return (
      <div id=”content”>
        <h1>Draft.js Editor</h1>
        <button onClick={this._onBoldClick.bind(this)}>Bold</button>
        <div className=”editor”>
          <Editor
            editorState={this.state.editorState}
            onChange={this.onChange}
          />
        </div>
      </div>
    );
  }
}

Upvotes: 2

Views: 1216

Answers (1)

kkkkkkk
kkkkkkk

Reputation: 7748

You could convert editorState to raw JS in order to store it in DB:

import {
  convertToRaw,
} from 'draft-js';

export default class App extends React.Component {
  // ...
  saveToDb() {
    const contentState = this.state.editorState.getCurrentContent();

    const rawContent = JSON.stringify(convertToRaw(contentState));

    Meteor.call(/* save rawContent to db */);
  }
  // ...
}

Then to convert rawContent back to editorState:

import {
  convertFromRaw,
  EditorState,
} from 'draft-js';

const rawContent = /* get this value from db */;

const contentState = convertFromRaw(JSON.parse(rawContent));

const editorState = EditorState.createWithContent(blocks);

Upvotes: 2

Related Questions