Recupero dei dati con createAsyncThunk
Scorri per mostrare il menu
Cosa Stai Realizzando
Recupero di dati da un'API utilizzando Redux Toolkit.
Creazione di un'Azione Asincrona
Redux Toolkit fornisce createAsyncThunk per gestire la logica asincrona.
import { createAsyncThunk } from '@reduxjs/toolkit';
export const fetchPosts = createAsyncThunk(
'posts/fetchPosts',
async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
return response.json();
}
);
Collegamento allo Slice
Gestione dell'azione asincrona all'interno dello 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 consente di gestire la logica asincrona in modo strutturato. Tiene traccia automaticamente degli stati di caricamento, successo ed errore.
Tutto è chiaro?
Grazie per i tuoi commenti!
Sezione 5. Capitolo 2
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Sezione 5. Capitolo 2