4

I'm new to React. I have an assignment building a Markdown Editor with Blockstack ID integrated.

I'm trying to save the content into a JSON file then load it again in the editor, but it seems like it can't load that JSON file back to the editor.

Here's some code:

import MDEditor from '@uiw/react-md-editor';

    <MDEditor
       onChange={e=>this.updateMarkdown(e)}
       value={this.state.markdown}
    />


             <button
              onClick={e => this.saveNewText(e)}>
              Submit Changes
             </button>

  updateMarkdown(editor, data, value) {
    this.setState({ markdown: value})
  }


  saveNewText() {
    const { userSession } = this.props
    let currentDocument = this.state.currentDocument
    let newDocument = {
      md: this.state.markdown,
      created_at: Date.now()
    }

    const options = { encrypt: true }
    userSession.putFile('Document.json', JSON.stringify(newDocument), options)
      .then(() => {
        this.setState({
          currentDocument:newDocument
        })
      })
   }

  loadNewText() {
      const { userSession } = this.props
      const options = { decrypt: true }
      userSession.getFile('Document.json', options)
      .then((file) => {
          var docFile = JSON.parse(file || '[]');
          this.setState({
            currentDocument:docFile,
            markdown:docFile.md
          });
      })
    }

  componentWillMount() {
    const { userSession } = this.props
    this.setState({
      person: new Person(userSession.loadUserData().profile),
      username: userSession.loadUserData().username
    });
    this.loadNewText();
Jin
  • 41
  • 1

1 Answers1

1

The react-blockstack package provides a useFile hook for React to persist content in the Blockstack Gaia storage:

const [document, setDocument] = useFile('Document.json')

This replaces most of your code except transformation between text and JSON.

Terje Norderhaug
  • 3,649
  • 22
  • 25