Replace text

Hello Everyone,

In prosemirror, I want to replace after word that we type with a translated text. I have tried writing an InputRule that takes a word and calls the api for translated word. But It’s not working because I believe its asynchronous. Here is the code.

new InputRule(/[a-zA-Z]+\s/i,  (state, match, start, end) => {
      if (!match[0]) {
        return null;
      }
    // utils.convertText takes a word, calls the api and returns translated word.
      utils.convertText(match[0]).then((res) => {
        let tr = state.tr.insertText(
          res,
          start - 1,
          end                    
        )        
      return tr;
      })                                   
    })

So my question is, how can I replace the words asynchronously ?

Thank you.

Observe transactions and store pending translateable words in some plugin state (keeping their position up to date as more changes come in). Then, in a view plugin, start the asynchronous fetching of translactions for those pending words, and when they come in, replace the appropriate ranges in the current document.

2 Likes