Skip to content

Instantly share code, notes, and snippets.

@sruli
Last active April 10, 2019 10:50
Show Gist options
  • Save sruli/ee2701a25a7ac05f7309ded3a55ea26f to your computer and use it in GitHub Desktop.
Save sruli/ee2701a25a7ac05f7309ded3a55ea26f to your computer and use it in GitHub Desktop.
import { EditorState, ContentState, convertFromRaw } from 'draft-js';
const editorStateReducer = (state = defaultEditorState, action) => {
switch(action.type) {
case MORE_CONTENT_RETRIEVED: {
// Capture current state
const currentContentState = state.getCurrentContent();
const currentBlockMap = currentContentState.getBlockMap();
const currentSelection = state.getSelection();
// Create new ContentBlocks
const { blocks } = action.payload;
const newContentState = convertFromRaw({ blocks, entityMap: {} });
const newBlockMap = newContentState.getBlockMap();
// Combine new and existing ContentBlocks
const combinedBlockMap = newBlockMap.concat(currentBlockMap);
const combinedContentState = ContentState.createFromBlockArray(combinedBlockMap.toArray());
// Push EditorState while excluding changes from undo/redo stack
const stateNoUndo = EditorState.set(state, { allowUndo: false });
const newState = EditorState.push(stateNoUndo, combinedContentState, 'insert-fragment');
const stateAllowUndo = EditorState.set(newState, { allowUndo: true });
// Maintain SelectionState
const newStateWithSelection = EditorState.forceSelection(stateAllowUndo, currentSelection);
// Return combined selection state
return newStateWithSelection;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment