You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
10 Hrs
40 Min
50 Seg

C贸mo integrar la API de Platzi Store

9/22
Resources

How to set up an API in a project with React and Axios?

Integrating an API into a React project can significantly increase its functionality and dynamism. By applying optimization techniques using tools like Webpack and Axios, the process becomes more efficient. Here, I'll show you how to properly configure an API using the Axios library to facilitate HTTP requests and manage information in an organized way.

What is the first step when working with APIs and React?

First, you need to have an API ready that you can use. This API will provide you with the necessary data to integrate into your application. Once you have the URL, proceed to configure it in your React project, closing unnecessary elements to work efficiently.

How to implement a hook in React to handle API requests?

  1. Create a custom hook: Inside the src folder, generate a subfolder called hooks and inside it, a useInitialState.js file.

  2. Import useEffect and useState: These React hooks are key to manage side effects and local state.

import { useEffect, useState } from 'react';
  1. Install Axios: In your terminal, add Axios as a dependency to handle HTTP requests.

    npm install axios
  2. Configure the API: Define the API in your code with the provided URL.

    const API = 'URL_of_your_API';
  3. Create the hook function: Implement a function with the use convention, integrating state logic and effects.

    const useInitialState = () => { const [products, setProducts] = useState([]);    
     useEffect((() => { const fetchData = async () => { const response = await axios(API); setProducts(response.data); }; fetchData(); }, []);
     return products;};
    export default useInitialState;

How is the hook integrated into the main component of the application?

  • Import the hook into the main component: In the file where react-router is handled, import useInitialState.

    import useInitialState from './hooks/useInitialState';
  • Implements the hook and validates data: Assigns the data returned by the hook to a constant and performs validations to ensure that there are no errors in the display.

    const App = () => { const initialState = useInitialState();
     const isEmpty = Object.keys(initialState).length === 0;
     return ( <> {!isEmpty ? ( <RenderComponent  products={initialState.products}/> ) : ( <h1>Loading...</h1> )} </> );};

What additional configurations are required for Axios and async/await?

To ensure that Axios and async/await functionality behave properly in your React project, you must configure Babel with the appropriate plugins.

  • Configure Babel for async/await: Install a specific plugin that facilitates the use of async/await.

    npm install @babel/plugin-transform-runtime --save-dev
  • Add the plugin in Babel: In the .babelrc file, include the plugin under the plugins section.

    { " plugins": ["@babel/plugin-transform-runtime"]}

With these configurations ready, run your application with npm run start. Watch how the project handles API requests, displaying load messages while waiting for data and validating the correct reception of the data. Working with Axios and react-hooks like useEffect and useState optimizes the development of your React projects. Keep honing your skills in each class to expand your mastery of the subject!

Contributions 7

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

La api esta caida :c

Para el manejo de peticiones as铆ncronas con Async/Await usamos el plugin @babel/plugin-transform-runtime .

npm i @babel/plugin-transform-runtime -D

C贸mo integrar la API de Platzi Store

https://us-central1-gndx-fake-api.cloudfunctions.net/api

  • Crearemos un hook para trabajar directamente con el llamado de esta API
    1.- Creamos una carpeta en src llamada hooks.
    2.- Creamos un archivo dentro de hooks > llamado useInitialState.js
    3.- Instalamos axios con: npm install axios -S
    4.- Instalamos: npm install @babel/plugin-transform-runtime -D
    5.- Actualizamos .babelrc
{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    "babel-plugin-transform-class-properties",
    "@babel/plugin-transform-runtime"
  ]
}

App.jsx:

import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Home from '../containers/Home';
import Checkout from '../containers/Checkout';
import Layout from '../components/Layout';
import NotFound from '../containers/NotFound';

import useInitialState from '../hooks/useInitialState';

const App = () => {
  const initialState = useInitialState();
  const isEmpty = Object.keys(initialState.products).length;
  return (
    <>
    {isEmpty > 0 ? (
        <BrowserRouter>
          <Layout>
            <Switch>
              <Route exact path="/" component={Home} />
              <Route exact path="/checkout" component={Checkout} />
              <Route component={NotFound} />
            </Switch>
          </Layout>
        </BrowserRouter>
      ) : <h1>Loading ...</h1>}
    </>
  )
}

export default App;

useInitialState.js :

import { useEffect, useState } from 'react';
import axios from 'axios';

const API = 'https://us-central1-gndx-fake-api.cloudfunctions.net/api';

const useInitialState = () => {
    const [products, setProducts] = useState([]);

    useEffect(async () => {
        const response = await axios(API);
        setProducts(response.data);
    }, []);

    return {
        products,
    }
}

export default useInitialState;

Buenas! Les dejo mi versi贸n del hook useInitialState.
Este hook no utiliza la librer铆a Axios por lo cual no hay necesidad de instalarla.
Espero les ayude 馃槂

import { useState, useEffect} from "react";

const API= "https://us-central1-gndx-fake-api.cloudfunctions.net/api";

const useInitialState = () => {
  try {
    const [products, setProducts] = useState([]);

    useEffect(async () => {
      const response = await fetch(API);
      const data = await response.json();
      setProducts(data);
    }, []);

    return {
      products
    };
  } catch (error) {
    return {
      products: [],
      error: typeof error === "object" ? error.message : error
    }
  }
}

export default useInitialState;

Recuerden a帽adir la carpeta dist al archivo .gitignore para que no suban esta carpeta a su repositorio remoto

Si no les fuinciona la API que est谩 en los recursos pueden usar la nueva API de Platzi en: https://fakeapi.platzi.com/ El objeto json que retorna es un poco diferente, pero funcionar谩: Aqu铆 el endpoint: https://api.escuelajs.co/api/v1/products

La API a no funciona 馃槮