DEV Community

Vicky Vasilopoulou
Vicky Vasilopoulou

Posted on

Fetch Data using TypeScript and React Query

Let's get started!

Let's say we have some data from an API and we want to use ReactQuery to fetch that data. Here is my approach.

Firstly install ReactQuery and also you can read these information below:
https://react-query.tanstack.com/

I am using Firestore for these purposes.

Create an endpoints.ts file and add your api endpoint such as:

const EXAMPLE_DATA = `example/`

Enter fullscreen mode Exit fullscreen mode

Create a request.models.ts file where we are gonna add all they different types of our API call. For instance if your API had a cats[] then you can do inside the file ->

The key-data below is your key on the JSON data that you receive

export interface CatsData {
  animal: string,
  name: string,
  id: string
}

export interface CatsDataModel {
  data: CatsData[]
}
Enter fullscreen mode Exit fullscreen mode


js
In case you have a jwt token create an interface for that as well

 export interface TokenRequestModel {
  jwt: string
}
Enter fullscreen mode Exit fullscreen mode

Create a getCatsData.ts file. Bearer is Firebase's
Authorisation, other system using a different keyword.

export interface CatsDataModel {
  dataSummary: CatsData[]
}

export type GetCatsDataResponse = APIResponse<CatsDataModel>

export type GetCatsDataAxiosResponse = AxiosPromise<GetCatsDataResponse>

export const getCatsData = ({
  jwt,
}: TokenRequestModel): GetCatsDataAxiosResponse => {
 return axios({
  method: 'GET',
  url:(EXAMPLE_DATA)
headers: {
    Authorization: `Bearer ${jwt}`
  }
})
}
Enter fullscreen mode Exit fullscreen mode

Now on your main file where you want to render your data
The useUserContext is a customised hook build on the Auth.ts file that has the signIn function for firebase.

const {idToken} = useUserContext()
const { data: dataSummary } = useQuery(
 ['dataSummary'],
() => getCatsData({ jwt: idToken }),
{
 enables: !!idToken
 }
)
Enter fullscreen mode Exit fullscreen mode

See you next Time!!

Top comments (5)

Collapse
 
mohdahmad1 profile image
Mohd Ahmad • Edited

Please add syntax highlighting, it will be easier to read.

Collapse
 
vikirobles profile image
Vicky Vasilopoulou

Thank you very much quite new on this site.

Collapse
 
mohdahmad1 profile image
Mohd Ahmad

Add it like github

console.log('hello world');
Enter fullscreen mode Exit fullscreen mode

Here is the screenshot
image

Thread Thread
 
vikirobles profile image
Vicky Vasilopoulou

It was like that before the first change I put it back now hope it looks as it should. thanks

Thread Thread
 
mohdahmad1 profile image
Mohd Ahmad

```js
let x = 100
```
Produces

let x = 100
Enter fullscreen mode Exit fullscreen mode

```
let x = 100
```
Produces

let x = 100
Enter fullscreen mode Exit fullscreen mode

Notice js after ``` or backticks you prefer