image

Unlimited bootcamps + English course forever

80
%OFF
Article image
Ruben Ramos
Ruben Ramos22/09/2024 21:29
Share

Consumo de APIs em React

  • #React

Exempo de Consumo de APIs em React Usando

Fetch

Axios

React Query

Neste exemplo iremos listar os repostiros de um usuário do Github

Types.tsx

type Repository = {
full_name: string;
description: string | null;
};


export default Repository;

URL.tsx

const URL = "https://api.github.com/users/ruben-com-br/repos"

export default URL;

Exemplo em Axios e Fetch(comentado)

import { SetStateAction, useEffect, useState } from "react";
import Repository from './Types';
import URL from './URL'
import axios from "axios";


function ApiAxios() {
const [repositories, setRepositories] = useState<Repository[]>([]);


useEffect(() => {
  //fetch(URL)
  axios.get(URL)


    // .then((response) => response.json())
    // .then((data) => { 
    //   setRepositories(data);
    // })


    .then((response: { data: SetStateAction<Repository[]>; }) => {
      setRepositories(response.data);
    })
}, []);


return (
  <div>
    <h1>Consumo de api em Axios</h1>
    <h2>Lista de Repositorios</h2>


    <ul>
      {repositories.map((repo) => (
        <li key={repo.full_name}>
          <strong>{repo.full_name}</strong>
          <p>{repo.description}</p>
        </li>
      ))}
    </ul>
  </div>
);
}


export default  ApiAxios;

Exemplo em React Query

api.tsx

import axios from "axios";
import Repository  from "../Types";
import URL from "../URL";


async function getUsers(): Promise<Repository[]> {
const response = await axios.get<Repository[]>(`${URL}`);


return response.data;
}


export const api = {
getUsers,
};

api-react-query.tsx

import { useQuery } from "react-query";
import { api } from "./api";


function ApiReactQuery() { 
const { data, isError, isLoading } = useQuery("repo", api.getUsers);


return (
  <div>
    {isLoading && <h3>Carregando...</h3>}
    {isError && <h3>Ocorreu algum problema :(</h3>}
    <h1>Consumo de api em React Query</h1>
    <h2>Lista de Repositorios</h2>
    {data?.map((repo) => (
      <li key={repo.full_name}>
        <strong>{repo.full_name}</strong>
        <p>{repo.description}</p>
      </li>
    ))}
  </div>
);
}


export default ApiReactQuery;

Código: https://github.com/ruben-com-br/consumo-api-react

Link: https://ruben-consumo-api-react.netlify.app/

me siga:

ruben.com.br/in

Share
Recommended for you
Deal Group - AI Centric .NET
Randstad - Análise de Dados
BairesDev - Machine Learning Training
Comments (0)