Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Property 'results' does not exist on type 'AxiosResponse<any, any>' with axios

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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`)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading