#HTML-Entities - error decode function

5 messages · Page 1 of 1 (latest)

noble ridge
#

Hello Everyone,

in the quizzical project I run into a problem with the imported decode-function to decode html-entities.

Sometimes when I run the decode-function I will get an error message "text.substring is not a function" and the quiz component won't render. When I reload the page and try it again sometimes it works just fine and sometimes I get the message multiple times in a row. Sometimes everything works and then when doing the quiz the third or fourth time the error appears.
My guess is, there are some characters that only appear in some of the questions from the API that throw this error, but unfortunately I couldn't figure out so far what options I should add to the decode function to solve this issue. I tried a couple different options and I always end up with the same error.
Does anybody have a suggestion?

Here is my relevant code:
(
import {decode} from "html-entities";

async function getQuestions(){
  
    const response = await fetch(getApiTag(questionParameters));
    const data = await response.json();

    setQuizArray( data.results.map(component => {
        return(
            {
                id: uuidv4(),
                question: decode(component.question ),
                answers: insertAnswerAtRandomPosition(decode(component.incorrect_answers), decode(component.correct_answer)),
                correctAnswer: decode(component.correct_answer),
                selected: ""                 
            }
        )
        
    }))  
}

)

valid gale
#

@noble ridge There's a possibility that the package has a bug. In this situation you can try a different package like this https://www.npmjs.com/package/he or alternatively just create your own decode function like the one below:

function decodeHtml(html) {
  var txt = document.createElement('textarea');
  txt.innerHTML = html;
  return txt.value;
}
noble ridge
#

@valid gale thank you very much for the tip. I used the different package and so far no problems with decoding anymore. The help is very much appreciated 🙂

valid gale
#

👍

versed fable
#

@noble ridge In the original error, it looks like you are calling decode(component.incorrect_answers). I believe that component.incorrect_answers is an array, but the decode function expects a string as the first argument. That is probably the source of the error.