Skip to content
Advertisement

Unpredictable state change

I am dynamically creating mathlive fields and adding them to the DOM.

Though it isn’t a good way but doing it like this because I wasn’t able to add the element as a React component and I needed a workaround quickly

Now when I remove an element from array responsible for rendering the elements, it works as expected but when the input event is fired on any of the remaining mathlive fields, the array comes back into the previous state before the element was removed.

const defaultOptions = [
    { text: '' },
    { text: '' },
    { text: '' },
    { text: '' },
]
const [options, setOptions] = useState(defaultOptions)

useEffect(() => {
    if (isPhysicsMathType) {
        options.map((option, i) => {
            addMathfield(option, i)
        })
    }
}, [isPhysicsMathType])

const addMathfield = (option, i) => {
    const mfe = new MathfieldElement()
    mfe.setAttribute('virtual-keyboard-mode', 'manual')
    mfe.value = option.text
    mfe.addEventListener('input', ev => {
        handleOptionChanged(ev, i)
    })
    let parent = null;
    const elementSelectInterval = setInterval(() => {
        parent = document.querySelector('.mathfield' + i)
        if (parent) {
            parent.appendChild(mfe)
            clearInterval(elementSelectInterval)
        }
    }, 50)
}

Rmoving the last option from the options array

const handleRemoveOption = () => {
    const choices = [...options]
    choices.pop()
    setOptions(choices)
}

Rendering elements

options.map((option, i) => {
 return <div key={"option" + i} className={'mathfield' + i}></div>
})

Advertisement

Answer

The problem is solved by changing the input listener to blur. The issue was that I was always modifying the options array on every input (which is still weird why it wasn’t working with that?). Now the options are modified after the blur event is fired on the mathfield.

mfe.addEventListener('blur', ev => {
  handleOptionChanged(ev, i)
})
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement