opentrivia api를 통해 데이터 적용하기(문제 맞추기)

개발공부·2022년 10월 21일
0

VUE 공부하기

목록 보기
4/5

* 상황

  • 기존 questions 값은 일일히 사람이 만들어서 작업, api를 통해 문제와 답안을 받는 것이 필요(대다수의 문제 하나 - 문항 4개로 이루어져 있으나 문제 하나 - 문항 2개로 이루어진 것도 필요)
  • 기존 questions
 const questions = [
      {
        question:
          "Which programming language shares its name with an island in Indonesia?",
        answer: 1,
        choices: ["Java", "Python", "C", "Jakarta"],
      },
      {
        question: "On Twitter, what is the character limit for a Tweet?",
        answer: 3,
        choices: ["120", "160", "140", "100"],
      },
      {
        question: "What does the 'MP' stand for in MP3?",
        answer: 4,
        choices: [
          "Music Player",
          "Multi Pass",
          "Micro Point",
          "Moving Picture",
        ],
      },
    ];

1. openTribia

https://opentdb.com/api_config.php
▶ 컴퓨터 관련 문제 - 문항을 만듦

https://opentdb.com/api.php?amount=10&category=18

  • onMounted에 fetch 함수를 넣음
    - onMounted : 라이프사이클 훅으로, 구성요소가 마운트된 후 호출될 콜백을 등록함
const fetchQuestionsFromServer = async function () {
      console.log("fetch questions from server");
      fetch("https://opentdb.com/api.php?amount=10&category=18")
        .then((res) => {
          //console.log(res);
          return res.json();
        })
    };

    onMounted(() => {
      fetchQuestionsFromServer();
    });

2. 가져온 데이터에서 이름 붙이기

▶ openTribia에서 만든 링크에서 가져온 필요한 데이터들은 노랑색으로 표시
▶ 기존의 question, choices, answer값으로 template이 만들어짐
▶ 반면 노랑색 표시와 기존의 데이터 이름이 같지 않음
이 둘을 같게 만들어야 함

const fetchQuestionsFromServer = async function () {
      fetch()
        .then((data) => {
          const newQuestions = data.results.map((serverQuestion) => {
          //기존 데이터 이름과 api 데이터 이름을 같게 만들기 위함
            const arrangedQuestion = {
              question: serverQuestion.question,
              choices: "",
              answer: "",
            };
            // console.log("arrangedQuestion", arrangedQuestion);
            const choices = serverQuestion.incorrect_answers;
            //Math.random()은 0에서 1사이, 1~ 4까지 하기 위해 +1
            //Math.floor()는 정수 반환하기 위함
            arrangedQuestion.answer = Math.floor(Math.random() * 4 + 1);
            //맞는 답만 들어가게 할 것 (1)
            choices.splice(
              arrangedQuestion.answer - 1,
              0,
              serverQuestion.correct_answer
            );
            arrangedQuestion.choices = choices;
            return arrangedQuestion;
          });
          console.log("new formatted questions", newQuestions);
          questions.value = newQuestions; //question.value값에 들어갔음이 중요
          console.log("questions", questions);
          questions.length = questions.value.length;
          console.log("questions 길이", questions.value.length);
          //문제를 맞히고 난 뒤 문제가 로딩되고 타이머가 다시 시작되야 함
          loadQuestion(); 
          countDownTimer();
        });
    };

* (1)번 참고

choices.splice(arrangedQuestion.answer - 1,0,serverQuestion.correct_answer);

출처 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

const months = ['Jan', 'March', 'April', 'June'];

months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

months.splice(-1, 0, "Test");
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "Test", "May"]

months.splice(-1, 0, "Test2");
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "Test", "Test2", "May"]

3. 기존 함수에 questions 값 변경

[기존]

 const loadQuestion = () => {
      canClick = true;
      // Check if there are more questions to load
      if (questions.length > questionCounter.value) {
        // load question
        timer.value = 100;
        currentQuestion.value = questions[questionCounter.value];
        console.log("Current questions", currentQuestion.value);
        questionCounter.value++;
      } else {
        // no more questions
        endOfQuiz.value = true;
        console.log("Out of questions");
      }
    };

[변경]

const loadQuestion = () => {
      canClick = true;
      // Check if there are more questions to load
      if (questions.value.length > questionCounter.value) {
        //값이 바뀔 때 value 넣기
        // load question
        timer.value = 100;
        currentQuestion.value = questions.value[questionCounter.value];
        console.log("Current questions", currentQuestion.value);
        questionCounter.value++;
      } else {
        // no more questions
        endOfQuiz.value = true;
        console.log("Out of questions");
      }

4. 결과




profile
개발 블로그, 티스토리(https://ba-gotocode131.tistory.com/)로 갈아탐

0개의 댓글