DraftJS triggers content change on focus?
I posted this answer to your question on github earlier today, but I'll add it here as well for future reference:
You're right in that onChange is called every time the editorState
changes. And since the editorState
holds both the selectionState
and the contentState
, it will change both when there's a content edit, and when the selection/focus changes.
If you want to know if the change that triggered the onChange
method was in the contentState
or in the selectionState
, you could compare them with their old values:
function onChange(newState) {
const currentContentState = this.state.editorState.getCurrentContent()
const newContentState = newState.getCurrentContent()
if (currentContentState !== newContentState) {
// There was a change in the content
} else {
// The change was triggered by a change in focus/selection
}
}
Now, if you know that the change was in the contentState
, you can get some more info by calling newState.getLastChangeType(). It should return any of these values (unless you, or some plugin you've added, have created new change types).
However, sometimes just the conditional if (currentContentState !== newContentState)
not work and not detect the change for cases like when you to modify the content state using Entity.mergeData
together with forceSelection
because this change is stored inside entity and is not exposed in contentState
.
So you could do something like that additionaly.
this.currentEntityMap = null;
function onChange(newEditorState) {
const currentContentState = editorState.getCurrentContent();
const newContentState = newEditorState.getCurrentContent();
const newContentStateRaw = convertToRaw(newContentState);
const newEntityMap = newContentStateRaw ? newContentStateRaw.entityMap : null;
//so if you have the two entity maps, you can to compare it, here an example function.
const isEntityMapChanged = this.isEntityMapChanged(newEntityMap);
this.currentEntityMap = newEntityMap;
}
isEntityMapChanged(newEntityMap) {
let isChanged = false;
if (this.currentEntityMap) {
loop1:
for (const index of Object.keys(newEntityMap)) {
if (this.currentEntityMap[index] && newEntityMap[index].type === this.currentEntityMap[index].type) {
loop2:
for (const prop of Object.keys(newEntityMap[index].data)) {
if (newEntityMap[index].data[prop] !== this.currentEntityMap[index].data[prop]) {
isChanged = true;
break loop1;
}
}
} else {
isChanged = true;
break loop1;
}
}
}
return isChanged;
}
then to used the flag isEntityMapChanged
and the first conditional for to do the save.