Modern Way - Using Asynchronous Thunk Functions
Redux Toolkit এর createAsyncThunk
দিয়ে async operations অনেক সহজ হয়ে যায়। Automatic loading states এবং error handling পাওয়া যায়।
কোড
Post Slice
postSlice.js
const { createSlice, createAsyncThunk } = require("@reduxjs/toolkit");
// Async Thunk
const fetchPosts = createAsyncThunk(
'posts/fetchPosts',
async () => {
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos?_limit=5"
);
const posts = await response.json();
return posts;
}
);
// Initial State
const initialState = {
loading: false,
posts: [],
error: "",
};
const postSlice = createSlice({
name: "posts",
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchPosts.pending, (state) => {
state.loading = true;
state.error = "";
})
.addCase(fetchPosts.fulfilled, (state, action) => {
state.loading = false;
state.posts = action.payload;
})
.addCase(fetchPosts.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message;
state.posts = [];
});
},
});
module.exports = postSlice.reducer;
module.exports.fetchPosts = fetchPosts;
createAsyncThunk
automatically pending, fulfilled, rejected actions তৈরি করে। createAsyncThunk এর সুবিধা
Modern Way এর সুবিধা: - Automatic pending/fulfilled/rejected actions - Built-in error handling - কম boilerplate code - Cross-slice communication (extraReducers) - Consistent async patterns
extraReducers Syntax
// Old syntax (object notation)
extraReducers: {
["counter/increment"]: (state, action) => {
state.count += 1;
},
}
// New syntax (builder callback) - Recommended
extraReducers: (builder) => {
builder.addCase(counterActions.increment, (state, action) => {
state.count += 1;
});
}
Builder callback syntax recommended কারণ এটি TypeScript support এবং better IntelliSense দেয়।
Last updated on