Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Fetching Data with createAsyncThunk | Handling Async Logic with Redux Toolkit
Керування станом з Redux Toolkit у React

bookFetching Data with createAsyncThunk

Свайпніть щоб показати меню

What You Are Building

You will fetch data from an API using Redux Toolkit.

Creating an Async Action

Redux Toolkit provides createAsyncThunk to handle async logic.

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

export const fetchPosts = createAsyncThunk(
  'posts/fetchPosts',
  async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    return response.json();
  }
);

Connecting to the Slice

Handle the async action inside your slice:

import { createSlice } from '@reduxjs/toolkit';
import { fetchPosts } from './postsThunk';

const postsSlice = createSlice({
  name: 'posts',
  initialState: {
    items: [],
    status: 'idle',
    error: null
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchPosts.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchPosts.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.items = action.payload;
      })
      .addCase(fetchPosts.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message;
      });
  }
});

export default postsSlice.reducer;

createAsyncThunk lets you handle async logic in a structured way. It automatically tracks loading, success, and error states.

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 5. Розділ 2

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 5. Розділ 2
some-alt