La api esta caida :c
Introducci贸n
驴Por qu茅 usar Webpack?
Presentaci贸n del proyecto en React.js: PlatziStore
Webpack en el Backend
Instalaci贸n y configuraci贸n de Express.js
Configuraci贸n de Webpack para Express.js
Configuraci贸n de TypeScript
Preparar la API Rest con Express.js
Webpack en el Frontend
Migracion de Webpack 4 a Webpack 5
Configuraci贸n inicial de Webpack para PlatziStore
C贸mo integrar la API de Platzi Store
Integrando la API de Platzi Store
Webpack Alias
Manejo de assets en Webpack
Optimizaci贸n de im谩genes con Webpack y CDN
Integraci贸n con TypeScript
Hot Reload
Lazy Loading
Code Splitting en desarrollo
Code Splitting en producci贸n
Despliegue
Deploy de React en Netlify
Deploy de Express en Heroku
Comprar y conectar un dominio
Pr贸ximos pasos con Webpack
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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.
Create a custom hook: Inside the src
folder, generate a subfolder called hooks
and inside it, a useInitialState.js
file.
Import useEffect and useState: These React hooks are key to manage side effects and local state.
import { useEffect, useState } from 'react';
Install Axios: In your terminal, add Axios as a dependency to handle HTTP requests.
npm install axios
Configure the API: Define the API in your code with the provided URL.
const API = 'URL_of_your_API';
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;
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> )} </> );};
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
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
https://us-central1-gndx-fake-api.cloudfunctions.net/api
{
"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 馃槮
Want to see more contributions, questions and answers from the community?