Home > Back-end >  how to correctly display elements when API fetch returning HTML special entities (such as ")?
how to correctly display elements when API fetch returning HTML special entities (such as ")?

Time:08-24

I am fetching data from a trivia api, however the data I am retrieving is not in a format where I can readily display it, is there a problem with how I am fetching / storing the data? what is an easy fix?

Fetching & storing

  React.useEffect(() => {
    fetch("https://opentdb.com/api.php?amount=5&category=9&difficulty=medium")
      .then(res => res.json())
      .then(info => setData(info.results.map(item => {
        return { 
          type: item.type, 
          question: item.question, 
          correct_answer: item.correct_answer, 
          incorrect_answers: item.incorrect_answers,
          id: nanoid() 
        }})))
  }, [])

An example of how the raw data is currently being displayed

{
    "type": "multiple",
    "question": "What is the German word for "spoon"?",
    "correct_answer": "Löffel",
    "incorrect_answers": [
      "Gabel",
      "Messer",
      "Essstäbchen"
    ],
    "id": "8IfTTvpoQd8DaJ1Hx941a"
  },

as can see from above it is displaying the data as its raw special entities.

CodePudding user response:

You can install the package 'he' by following command

npm install he

in js

import { decode } from 'he';

const json = {
    type: 'multiple',
    question: 'What is the German word for "spoon"?',
    correct_answer: 'Löffel',
    incorrect_answers: ['Gabel', 'Messer', 'EssstÄbchen'],
    id: '8IfTTvpoQd8DaJ1Hx941a',
};
const jsonString = JSON.stringify(json, null, 4);
const decodedString = decode(jsonString)

in your HTML

<pre>
   <code>{he.decode(JSON.stringify(json, null, 4))}</code>
</pre>
  • Related