DEV Community

loading...

Fetch Data using TypeScript and React Query

vikirobles profile image Vicky V ・1 min read

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!!

Discussion (5)

pic
Editor guide
Collapse
zakiazfar profile image
zakiAzfar • Edited

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

Collapse
vikirobles profile image
Vicky V Author

Thank you very much quite new on this site.

Collapse
zakiazfar profile image
zakiAzfar

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 V Author

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

Thread Thread
zakiazfar profile image
zakiAzfar

```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