[Rick and Morty Characters Wiki] — Parte 2.5— Configuração — React Query + Tipagem

Wallyson Galvão
3 min readJan 21, 2023

--

Photo by Emre Turkan on Unsplash

Caso tenha caído aqui por acidente, essa é a parte 1 de uma serie de posts para implementação de uma aplicação inspirada no post Rick and Morty Character Wiki do Joy Shaeb:

0 — Rick and Morty Character Wiki

Instale a lib React Query:

yarn add @tanstack/react-query

App.tsx

import React from 'react';
import { StatusBar } from 'react-native';
import { ThemeProvider } from 'styled-components';

// Importação da lib @tanstack/react-query
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

import { theme } from './styles';
import { Routes } from './routes';

import './config';

const queryClient = new QueryClient(); // Adicionar essa linha

const App = () => {
return (
{/** Adicione este bloco de código **/}
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={theme}>
<StatusBar barStyle={'dark-content'} />
<Routes />
</ThemeProvider>
</QueryClientProvider>
);
};

export default App;

Para um melhor aproveitamento do typescript, crie uma pasta chamada types na raiz do projeto, e adicione 2 arquivos dentros dela, o common.ts e o response.ts:

src/types/common.ts — é arquivos de tipagem dos objetos que temos na API do Rick and Morty

export type Info = {
count: number;
pages: number;
next: string;
prev: null;
};

export type Status = 'Alive' | 'Dead' | 'unknown';

export type Species =
| 'Human'
| 'Alien'
| 'Humanoid'
| 'Poopybutthole'
| 'Mythological'
| 'Unknown'
| 'Animal'
| 'Disease'
| 'Robot'
| 'Cronenberg'
| 'Planet';

export type Gender = 'Female' | 'Male' | 'Genderless' | 'unknown';

export type Character = {
id: number;
name: string;
status: Status;
species: Species;
type: string;
gender: Gender;
origin: {
name: string;
url: string;
};
location: {
name: string;
url: string;
};
image: string;
episode: string[];
url: string;
created: Date;
};

export type Episode = {
id: number;
name: string;
air_date: string;
episode: string;
characters: string[];
url: string;
created: Date;
};

export type Location = {
id: number;
name: string;
type: string;
dimension: string;
residents: string[];
url: string;
created: Date;
};

src/types/response.ts — é o arquivos de respostas que vamos utilizar junto ao @tanstack/react-query:

import { Character, Episode, Info, Location } from './common';

export type CharactersResponse = {
info: Info;
results: Character[];
};

export type EpisodesResponse = {
info: Info;
results: Episode[];
};

export type LocationsResponse = {
info: Info;
results: Location[];
};

Crie o arquivo src/services/requests/characters/queries.ts — aqui guardaremos nossas funções de requisições para a API, já incluindo a tipagem:

import api from '~/services/api';

import { CharactersResponse } from '~/types/response';

/**
* It makes a GET request to the /character endpoint, and returns the data from the
* response
* @returns A promise that resolves to an object with a data property that is of
* type CharactersResponse.
*/
export async function getCharacters() {
const { data } = await api.get<CharactersResponse>('/character');
return data;
}

Vamos utilizar o método useQuery da lib @tanstack/react-query para realizar nossa requisição:

import React from 'react';
import { Text, View } from 'react-native';
import { useQuery } from '@tanstack/react-query';

import { getCharacters } from '~/services/requests/characters/queries';

import { theme } from '~/styles';

const Characters = () => {
const { data } = useQuery({
queryKey: ['characters'],
queryFn: () => getCharacters(),
});

return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ color: theme.colors.blue }}>
{JSON.stringify(data?.results[0].name)}
</Text>
</View>
);
};

export default Characters;

Resultado

--

--