I’m following this guide to figure out how to work with State Field.
I modified the example and can’t make my custom variable updated. What am I doing wrong?
let editorView;
let countDocChanges = StateField.define({
create() { return 0 },
update(value, tr) {
if (tr.updateCount !== undefined) {
return tr.updateCount // Never gets called
}
return value
}
})
let state = EditorState.create({
doc: "...",
extensions: [countDocChanges]
})
editorView = new EditorView({
state,
parent: document.querySelector("#address-line")
});
function updateField(newValue) {
const tr = editorView.state.update({
updateCount: newValue
});
console.dir(tr) // No "updateCount" attr here
editorView.dispatch(tr);
console.log(editorView.state.field(countDocChanges)) // 0
}
updateField(5);
marijn
April 20, 2024, 1:19pm
2
Transactions don’t have an updateCount
property, and passing arbitrary properties to state.update
doesn’t do anything. You’ll want to define an annotation type and pass that to the transaction, then read it with the annotation
getter on the transaction.
1 Like
Thank you, it works now.
let editorView;
let count = 0;
let countDocChanges = StateField.define({
create() { return 0 },
update(value, tr) {
if (typeof(tr.annotations[0].value) === "object" && tr.annotations[0].value.newCount !== undefined) {
return tr.annotations[0].value.newCount
}
return value
}
})
let state = EditorState.create({
doc: "...",
extensions: [countDocChanges]
})
editorView = new EditorView({
state,
parent: document.querySelector("#address-line")
});
function updateField() {
count ++;
const tr = editorView.state.update({
annotations: Annotation.define().of({newCount : count})
});
editorView.dispatch(tr);
console.log(editorView.state.field(countDocChanges))
}
updateField();