Introduction to redux-thunk
redux-thunk
হলো একটি official middleware যা thunk functions handle করে। এটি আমাদের custom fetchAsyncMiddleware
এর মতোই কাজ করে।
প্রয়োজনীয় প্যাকেজ
terminal
npm install redux-thunk
redux-thunk vs Custom Middleware
middlewares.js
ফাইলের fetchAsyncMiddleware
যে কাজটা করতো thunk
সে কাজটাই করছে। তাই applyMiddleware()
এর মধ্যে fetchAsyncMiddleware
না দিয়ে thunk
দেওয়া হয়েছে। redux-thunk এর সুবিধা
redux-thunk এর সুবিধা: - Official Redux middleware - Well-tested ও optimized - Community support - TypeScript support - Simple ও lightweight
Data Flow
Usage Pattern
// Simple thunk
const incrementAsync = () => (dispatch) => {
setTimeout(() => {
dispatch({ type: 'INCREMENT' });
}, 1000);
};
// Thunk with API call
const fetchUser = (userId) => async (dispatch, getState) => {
dispatch({ type: 'FETCH_USER_START' });
try {
const response = await fetch(`/api/users/${userId}`);
const user = await response.json();
dispatch({ type: 'FETCH_USER_SUCCESS', payload: user });
} catch (error) {
dispatch({ type: 'FETCH_USER_ERROR', payload: error.message });
}
};
// Usage
store.dispatch(incrementAsync());
store.dispatch(fetchUser(123));
redux-thunk
দিয়ে complex async flows, error handling, loading states সব সহজেই manage করা যায়। কোড
Store with redux-thunk
const { createStore, applyMiddleware } = require("redux");
const { fetchTodos } = require("./functions");
const { default: thunk } = require("redux-thunk");
// ধাপ-1 Action Identifier
// ধাপ-2. Action অথাবা Action Handler অথবা Action Creator
// ধাপ-3. Initial State অথবা State
const initialState = {
todos: [],
};
// ধাপ-4. Reducer
const RD_todoReducer = (state = initialState, action) => {
switch (action.type) {
case "todos/todoAdded":
return {
...state,
todos: [...state.todos, { title: action.payload }],
};
case "todos/todoLoaded":
return {
...state,
todos: [...state.todos, action.payload],
};
default:
return state;
}
};
// ধাপ-5. Store
const store = createStore(
RD_todoReducer,
applyMiddleware(thunk)
);
// 5.a subscribe() এবং // 5.b getState()
store.subscribe(() => {
console.log(store.getState());
});
// 5.c dispatch()
store.dispatch(fetchTodos);
// Sync Action (commented)
// store.dispatch({
// type: "todos/todoLoaded",
// payload: "Learn Redux from LWS",
// });
redux-thunk
ব্যবহার করলে custom middleware লিখতে হয় না। Last updated on