Issue
When using axios for get data from a GET API from RapidAP, I get an array of JSON objects as seen in the pictures below. How can I use Typescript in React for just get the JSON objects'data within this array like my interface?
import React, { Component, useState , useEffect } from 'react';
import axios from 'axios';
const options: any = {
method: 'GET',
url: 'https://transfermarket.p.rapidapi.com/clubs/list-by-competition',
params: {id: 'ES1'},
headers: {
'x-rapidapi-host': 'transfermarket.p.rapidapi.com',
'x-rapidapi-key': 'mykey'
}
}
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
interface clubObjects {
id: string,
name: string,
image: string
}
Solution
It is pretty simple. Replace console.log(response.data);
with this code:
const data = await response.json(); setResponse(data);
setResponse
is storing the object this state:
const [response, setResponse] = useState<clubObjects[]>();
Notice <clubObjects[]>
, it sets the type of your state to an array of the clubObjects. Finally you can use .map
function to display data of each object within the array.
Answered By - Ahmad Bilal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.