Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Handling Async Data in the App | Building a Real Application with Redux Toolkit
Gestión de Estado con Redux Toolkit en React

bookHandling Async Data in the App

Desliza para mostrar el menú

Now you add data that comes from outside the app. Instead of starting with an empty list, you will load tasks from an API.

Creating the Async Action

Update your slice and add createAsyncThunk:

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

export const fetchTasks = createAsyncThunk('tasks/fetchTasks', async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos?_limit=5');

  if (!response.ok) {
    throw new Error('Failed to fetch tasks');
  }

  return response.json();
});

Handling Async States

Update your slice to track loading and errors:

const initialState = {
  items: [],
  status: 'idle',
  error: null
};

Add extraReducers:

extraReducers: (builder) => {
  builder
    .addCase(fetchTasks.pending, (state) => {
      state.status = 'loading';
    })
    .addCase(fetchTasks.fulfilled, (state, action) => {
      state.status = 'succeeded';
      state.items = action.payload;
    })
    .addCase(fetchTasks.rejected, (state, action) => {
      state.status = 'failed';
      state.error = action.error.message;
    });
}

Triggering the Fetch

Dispatch the action when the component loads:

import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { fetchTasks } from '../features/tasks/tasksSlice';

function TaskList() {
  const dispatch = useDispatch();

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

You added async logic to the application. Tasks are now loaded from an API, and the state tracks loading, success, and error states.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 7. Capítulo 4

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 7. Capítulo 4
some-alt