Display a list of products (Api) with React.js using useContext (Hook) / Mostrar una lista de productos (Api) con React.js usando useContext (Hook)

Tecnología
  
Programación Web
  
Nodejs
  
Javascript
  
Bootstrap
  
Desarrollo Web
  
React
    15 Febrero, 2021   Regresar el blog
Compartir:

Today we are going to learn how to use in a practical example useContext which is a react API to be able to handle the state very similar to what Redux would do, only in a simpler way, to To be able to carry out this example we are going to use an API that gives us https://fakestoreapi.com/ which provides us with false data to be used in our tests. En el día de hoy vamos a aprender a usar en un ejemplo práctico useContext el cual es una Api de react para poder manejar el estado muy similar a lo que haría Redux solo que de una manera más simple, para poder realizar este ejemplo vamos a usar una Api que nos brinda https://fakestoreapi.com/ el cual nos provee de data falsa para ser usada en nuestras pruebas.

React.js

To start we open the console / terminal and start the react project creator by typing

Para iniciar abrimos la consola/terminal e iniciamos el creador de proyectos de react escribiendo
npx create-react-app react-context-products

We will install the following main modules

Instalaremos los siguientes módulos
npm i redux bootstrap

useReducer = Define the status and update it / definir el estado y actualizarlo
We proceed to create two folders, the first one named components / and the second one context / inside components we will create two files called [ProductList.js - Item.js] and inside context we will create two files as well [ProductState - ProductReducer] Procedemos a crear dos carpetas la primera de nombre components / y la segunda context/ dentro de components crearemos dos archivos llamado [ProductList.js - Item.js] y dentro de context crearemos dos archivos tambien [ProductState - ProductReducer]

Let´s start / Empezamos

App.js
import Item from "./components/Item";
import ProductList from "./components/ProductList";
import "bootstrap/dist/css/bootstrap.min.css";
import ´./App.css´
import ProductState from "./context/ProductState";
function App() {
  return (
    <ProductState>
      <div className="container pt-3">
        <h3 className="text-center p-4">List of Product / Listado de productos</h3>
        <div className="row">
          <div className="col-4">
            <Item />
          </div>
          <div className="col-8">
          <ProductList />
          </div>
        </div>
      </div>
    </ProductState>
  );
}
export default App;

//CONTEXT

context/ProductState.js
import React, { useReducer } from "react";
import ProductReducer from "./ProductReducer";
import axios from "axios";
export const ProductContext = React.createContext();
export default function ProductState(props) {
  const initialState = {
    products: [],
    singleProduct: null,
  };
  const [state, dispatch] = useReducer(ProductReducer, initialState);
  const getAllProducts = async () => {
    const res = await axios.get("https://fakestoreapi.com/products");
    console.log(res.data);
    dispatch({
      type: "GET_ALL_PRODUCTS",
      payload: res.data,
    });
  };
  const getProductByID = async (id) => {
    const res = await axios.get("https://fakestoreapi.com/products/" + id);
    console.log(res);
    dispatch({
      type: "GET_PRODUCT_BY_ID",
      payload: res.data,
    });
  };
  return (
    <ProductContext.Provider
      value={{
        products: state.products,
        singleProduct: state.singleProduct,
        getAllProducts,
        getProductByID,
      }}
    >
      {props.children}
    </ProductContext.Provider>
  );
}

context/ProductReducer.js
export default function (state, action) {
  const { payload, type } = action;
  switch (type) {
    case ´GET_ALL_PRODUCTS´:
      return {
        ...state,
        products: payload,
      };
    case ´GET_PRODUCT_BY_ID´:
      return {
        ...state,
        singleProduct: payload,
      };
    default:
      return state;
  }
}

//COMPONENTS

components/ProductList.js
import React, { useEffect, useContext } from "react";
import { ProductContext } from "../context/ProductState";
const ProductList = () => {
  const { products, getAllProducts, getProductByID } = useContext(ProductContext);
  useEffect(() => {
    getAllProducts();
  }, []);
  return (
    <div className="list-group h-100">
      {products.map((p) => (
        <a className="list-group-item list-group-action d-flex flex-rows justify-content-between" href="#!" key={p.id} onClick={ () => { getProductByID(p.id)}}>
         <img src={p.image} className="img-fluid mr-4 " width="50"></img>
         <p>{p.title}</p>
         <code style={{fontSize:18}}>{p.price} $usd</code>
        </a>
      ))}
    </div>
  );
};
export default ProductList;

components/Item.js
import React, {useContext} from ´react´
import { ProductContext } from ´../context/ProductState´
export default function Item() {
    const { singleProduct } = useContext(ProductContext)
    return (
        <div >
            {singleProduct ? (<div className="card card-body text-center">
                <img src={singleProduct.image} className="card-img-top img-fluid m-auto " style={{width: 120}} />
                <h3 style={{color:´black´}}>{singleProduct.title}</h3>
                <code style={{fontSize:22}}>{singleProduct.price} $usd</code>
                <p>{singleProduct.description}</p>
                <button className="btn btn-success">Buy / Comprar</button>
                </div>) : (<h4>Select Item / Seleccione un producto</h4>)}
        </div>
    )
}

Live Demo: https://react-usecontext-example.herokuapp.com/









And with those friends we reached the end of the tutorial, I hope you enjoyed it and until next time!

Y con esa amigos llegamos al final del tutorial, espero que lo hayan disfrutado y hasta la próxima!

Visit my official website for budges and much more

Visita mi sitio web oficial para presupuestos y mucho más
TupaginaOnline.net

209 vistas
Compartir:


Autor
Jose Fuentes

- Web Developer -

 


0 COMENTARIO(S)
Contesta
Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *
Comentario *
Nombre *
Correo electrónico *
Sitio web

Articulos Relacionados
Articulos recientes

Desarrollos en venta

$ usd dólar 600