Search code examples
javascriptruby-on-railsreactjsdraftjs

How to use redux store to properly update EditorState in Draft.js


I am having a bit of difficulty setting a conditional that utilizes EditorState.createEmtpy() or EditorState.createWithContent(). Basically, if the fetched data contains a saved record, I want to display that content. If not, then I want EditorState.createEmtpy()

To start, here is my actual TextEditor container:

import React, { Component } from 'react';
import './styles/TextEditor.css';
import { Editor, EditorState, convertToRaw, convertFromRaw, ContentState} from 'draft-js';
import { connect } from 'react-redux';
import { addNewRecord, getRecord } from '../actions/recordActions.js';
import { bindActionCreators } from 'redux';

class TextEditor extends Component {
    constructor(props){
        super(props);
        this.state = {
            editorState: EditorState.createEmpty()
        }


            this.onChange = (editorState) => {
                const contentState = this.state.editorState.getCurrentContent();
                const editorStateJSONFormat = convertToRaw(contentState)
                this.props.addNewRecord(editorStateJSONFormat);
                this.setState({
                    editorState
                });
            }
        }


        componentDidMount = (props) => {
            this.props.getRecord()
        }

        componentWillReceiveProps = (nextProps, prevProps) => {
            let lastRecord;
            for (let i = nextProps.records.length; i > 0; i--){
                if (i === nextProps.records.length - 1){
                    lastRecord = nextProps.records[i].body
                }
            }
            const replaceRubyHashRocket = /=>/g
            const content = lastRecord.replace(replaceRubyHashRocket, ":")


            if (nextProps.records.length >= 1){
                this.setState({
                    editorState: EditorState.createWithContent(convertFromRaw(JSON.parse(content)))
                })
            } else{
                this.setState({
                    editorState: EditorState.createEmpty()
                })
            }
        }


    render(){
        return(
            <div id="document-container">
                <div >
                    <Editor 
                        editorState={this.state.editorState} 
                        onChange={this.onChange} 
                        placeholder="Type Below"
                        ref={this.setDomEditorRef}
                    />
                </div>
            </div>
        )
    }
}

const mapStateToProps = (state) => {
  return ({
    records: state.allRecords.records
  });
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({
    getRecord,
    addNewRecord
  }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(TextEditor)

Everything is working fine but I am completely lost as to what component lifecycle method I should be using.

As it stands, I can type something into the editor, refresh, and then the editor will display the correct content (the last element in the array). The problem is, when I go to add more content in the editor, I get an error that says content is undefined. It's like my loop getting the last element is now void?

For context, here is my reducer:

export default function manageDocuments(state = {loading: false,
}, action) {
    switch(action.type) {
        case 'PUSHING_RECORD':
            return {...state, loading: true}
        case "ADD_RECORD":
            return {...state, loading: false, records: action.payload}

        case "LOADING_RECORD":
            return {...state, loading: true}
        case "GET_RECORD":
            return {loading: false, ...state, records: action.payload}

        default:
            return {...state}
    }
};

Here is my action for POST/GET request from my Rails API.

import fetch from 'isomorphic-fetch';

export function addNewRecord(editorStateJSONFormat) {
    const request = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=utf-8', "Accepts": "application/json"
        },
        body: JSON.stringify({body: editorStateJSONFormat})
    }

    return (dispatch) => {
        dispatch({type: 'PUSHING_RECORD'});
        return fetch('http://localhost:3001/api/v1/documents', request)
            .then(response => response.json())
            .then(records => {
                dispatch({type: 'ADD_RECORD', payload: records})
        });
    }
}

export function getRecord() {
    return (dispatch) => {
        dispatch({type: 'LOADING_RECORD'});

        return fetch('http://localhost:3001/api/v1/documents', {method: 'GET'})
            .then(response => response.json())
            .then(records => dispatch({type: 'GET_RECORD', payload: records}));
        }
}

I combined reducers here (don't really need to at this point):

import { combineReducers } from 'redux';
import docsReducer from './docsReducer';

    export default combineReducers({
      allRecords: docsReducer
    })

I am pretty lost here. How could I achieve this?


Solution

  • For those wondering, this seemed to do the trick:

    componentWillReceiveProps = (nextProps) => {
        if (nextProps.records.length >= 1){
    
            let lastRecord;
            for (let i = nextProps.records.length; i > 0; i--){
                if (i === nextProps.records.length - 1){
                    lastRecord = nextProps.records[i].body
                }
            }
    
            const replaceRubyHashRocket = /=>/g
            const content = lastRecord.replace(replaceRubyHashRocket, ":")
    
            this.setState({
                editorState: EditorState.createWithContent(convertFromRaw(JSON.parse(content)))
            })
        }
    }
    

    Putting the logic inside the conditional, and removing:

    this.setState({
         editorState: EditorState.createEmpty()
    })
    

    allowed an empty document to be created if the DB is empty, or always return the last element in the array if the DB is not empty.

    Works fine!

    I know componentWillReceiveProps is deprecated but it was the only way I could accomplish what I needed to.