Extrayendo datos con React Redux/Toolkit

Extrayendo datos con React Redux/Toolkit

Hola amigos de la #nerdytud, espero que estén bien.

En el día de hoy quiero compartirles el paso a paso para la obtención de data proveniente de una API fake, por intermedio de react redux/toolkit.

Creación del proyecto

 npm init vite@latest redux-toolkit -- --template react

cd redux-toolkit

npm install

Agregado de librerías

npm install react-redux

npm install @reduxjs/toolkit

npm install axios

Dentro de la carpeta src, creamos un nuevo folder denominado store

Creación de productsSlice.jsx

import axios from "axios";
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

const initialState = {
  loading: false,
  products: [],
  error: ""
};

export const fetchProducts = createAsyncThunk("product/fetchProducts", () => {
  return axios
    .get("https://fakestoreapi.com/products")
    .then(res => res.data)
});

const productSlice = createSlice({
  name: "product",
  initialState,
  extraReducers: builder => {
    builder.addCase(fetchProducts.pending, state => {
      state.loading = true
    })
    builder.addCase(fetchProducts.fulfilled, (state, action) => {
      state.loading = false
      state.products = action.payload
      state.error = ""
    })
    builder.addCase(fetchProducts.rejected, (state, action) => {
      state.loading = false
      state.products = []
      state.error = action.error.message
    })
  }
});

export default productSlice.reducer;

Generación de archivo store.jsx

import { configureStore } from "@reduxjs/toolkit"
import productsSlice from "./productsSlice"

const store = configureStore({
  reducer: {
    product: productsSlice
  }
})

export default store

Modificación de App.js

import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { fetchProducts } from "./store/productsSlice";

export const App = () => {
  const product = useSelector(state => state.product);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchProducts());
  }, []);

  return (
    <div>
      <div>Productos Fake</div>


      {product.loading && <div>extrayendo datos de la API</div>}

      {!product.loading && product.error ? <div>Error: {product.error}</div> : null}

      {!product.loading && product.products.length ? (
        <div>
          {product.products.map((row, index) => (
            <div key={index}>
              <div>{row.title}</div>
              <div>${row.price}</div>
              <hr />
            </div>
          ))}
        </div>
      )
        :
        null
      }
    </div>
  );
}

export default App;

Modificación de main.jsx

import React from 'react'
import ReactDOM from 'react-dom/client'
import { Provider } from 'react-redux'
import App from './App'
import Store from './store/Store'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <Provider store={Store}>
      <App />
    </Provider>
  </React.StrictMode>
);

Ejecutar la aplicación

npm run dev

http://localhost:5173