Skip to content

Instantly share code, notes, and snippets.

@hchocobar
Last active January 26, 2024 20:15
Show Gist options
  • Save hchocobar/1000455ef0f3a6a85cc9a66924ee0b8c to your computer and use it in GitHub Desktop.
Save hchocobar/1000455ef0f3a6a85cc9a66924ee0b8c to your computer and use it in GitHub Desktop.
React consumiendo una API

React - Consumiendo API

Ejemplo

Genera un listado importando datos en formato JSON desde un sitio remoto

import React, { useState, useEffect } from "react";

export const Todos = () => {
  const [todos, setTodos] = useState();
  const host = 'https://jsonplaceholder.typicode.com/';
     
  const getTodos = async () => {
    const url = host + 'todos/';
    const options = {
      method: 'GET',
      redirect: 'follow'
    };
    
    const response = await fetch(url, options);
    if (!response.ok) {
      console.log('Error:', response.status, response.statusText)
      return response.status
    };
    const data = await response.json();
    setTodos(data);
  };

  useEffect(() => {
      getTodos();
    }, []);

  return (
    <div>
      <h3>Consumiendo API</h3>
      <p>Fuente: {url}</p>
      <ul>
         { !todos ? 'Cargando los datos desde la url ...' :
             todos.map( (todo, index) => {
                return <li key={index}>{todo.id} - {todo.title} - {todo.userId} - {todo.completed}</li>
             } )
         }
      </ul>
    </div>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment