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/`
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[]
}
js
In case you have a jwt token create an interface for that as well
export interface TokenRequestModel {
jwt: string
}
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}`
}
})
}
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
}
)
See you next Time!!
Top comments (5)
Please add syntax highlighting, it will be easier to read.
Thank you very much quite new on this site.
Add it like github
Here is the screenshot
It was like that before the first change I put it back now hope it looks as it should. thanks
```js
let x = 100
```
Produces
```
let x = 100
```
Produces
Notice js after ``` or backticks you prefer