I tried to make a rich text editor with real-time grammar checking functionality. I have my own dictionary and checking engine.
The problem here is the editor is not smooth as checking engine is run each time I make changes to draft.js editor even if I just move the cursor position.
Here is my RichTextEditor component.
import {updateEditorState, checkEditorState} from './logic/actions';
...
class RichTextEditor extends React.Component {
...
onChange = (editorState) => {
this.props.updateEditorState(editorState);
this.props.checkEditorState(editorState);
}
...
render() {
return (<Editor
editorState={this.props.editorState}
onChange={this.onChange}
/>);
}
}
const mapStateToProps = state => ({
});
const mapDispatchToProps = dispatch => ({
updateEditorState: bindActionCreators(updateEditorState, dispatch),
checkEditorState: bindActionCreators(checkEditorState, dispatch)
});
export default connect(mapStateToProps, mapDispatchToProps)(RichTextEditor);
logic/actions.js
import * as actionTypes from './rteActionTypes'
...
export const updateEditorState = (data) => {
return ({
type: actionTypes.UPDATE_EDITOR_STATE,
data: data
});
}
export const checkEditorState = (data) => {
return ({
type: actionTypes.CHECK_EDITOR_STATE,
data: data
});
}
...
logic/saga.js
import { takeLatest, all, call, put } from 'redux-saga/effects';
import * as actionTypes from './rteActionTypes';
import { checkEditorState } from './CheckEngine';
function* checkEditor(action) {
const {updated, editorState} = yield call(checkEditorState, action.data)
if (updated) {
yield put({ type: actionTypes.UPDATE_EDITOR_STATE, data: editorState })
}
}
export default function* saga() {
yield all([
takeLatest(actionTypes.CHECK_EDITOR_STATE, checkEditor)
]);
}
logic/reducer.js
import * as actionTypes from './rteActionTypes';
import {
EditorState,
CompositeDecorator,
convertFromRaw
} from 'draft-js';
const initialState = {
editorState: EditorState.createEmpty(decorator),
};
export default (state = initialState, action) => {
switch (action.type) {
case actionTypes.UPDATE_EDITOR_STATE:
return {
...state,
editorState: action.data
};
...
}
}
I know this implementation is not a good practise because the UI will be blocked until the redux action is dispatched successfully and that's the main reason for non-smooth editing. I want to make a background thread which detects the changes of store variable 'editorState'. Once the change is detected, it runs checkEngine and then dispatches a new redux action to update the editorState with grammar checked editorState.
But I don't know how to create a background thread or a worker for redux store in React.js Can you help me with this problem? Thanks.