Home > OS >  Property 'results' does not exist on type 'AxiosResponse<any, any>' with a
Property 'results' does not exist on type 'AxiosResponse<any, any>' with a

Time:06-12

I am trying to make an api call with async/await using typescript and access the results array in the response. But, it is throwing Property 'results' does not exist on type 'AxiosResponse<any, any>' error

Response format is:

data: {
  results: []
}

axios.ts

import axios from "axios";

export default axios.create({
    baseURL: process.env.API_ENDPOINT,
    headers: {
        "Content-type": "application/json"
    }
});

api.ts

import axios from "./axios";
import { shuffleArray } from "../utils";

export type Question = {
    category: string;
    correct_answer: string;
    difficulty: string;
    incorrect_answers: string[];
    question: string;
    type: string;
}

export type QuestionAnswers = Question & { answers: string[] }

export type Difficulty = "easy" | "medium" | "hard"

export const fetchQuestions = async (amount: number, difficulty: Difficulty) => {
    try {
        const { results } = await axios.get(`api.php?amount=${amount}&difficulty=${difficulty}&type=multiple`)
        return results.map((query: Question) => (
            {
                ...query,
                answers: shuffleArray([query.correct_answer, query.incorrect_answers])
            }
        ))
    } catch (error) {
        throw error;
    }
}

I tried fixing the error by defining an interface for response

interface QuestionResponse {
  results: Question[]
}

// and in api request
axios.get<QuestionResponse>(endpoint)

How can I fix this error ?

CodePudding user response:

Axios response schema looks as follows:

{
  data: {},
  status: 200,
  statusText: 'OK',
  headers: {},
  config: {},
  request: {}
}

That means your results will be available under data.results. Your API call should look like this:

const { data } = await axios.get(`api.php?amount=${amount}&difficulty=${difficulty}&type=multiple`)

CodePudding user response:

The primary return its data in the case of interface will be the type of data, but still returns data: INTERFACE | ANY

const { data } = await axios.get(`api.php?amount=${amount}&difficulty=${difficulty}&type=multiple`)
        return data.results.map((query: Question) => (...

so data if you do the below, you just typed your response data

const {data} = await axios.get<QuestionResponse>()....
  • Related