Skip to Content
🤖 Technology
Redux
8. Thunk Function

Understanding Thunk Function

Thunk মানে হচ্ছে কোন কিছুকে delay করা। এখানে fetchTodos হচ্ছে Thunk Function যা async operation করে।


Thunk Function কী?

Thunk Function হলো এমন একটি function যা অন্য function return করে। Redux এ এটি async actions handle করার জন্য ব্যবহৃত হয়।



Thunk Pattern

// Thunk Function Pattern const myThunk = (dispatch, getState) => { // Async operation setTimeout(() => { dispatch({ type: "SOME_ACTION", payload: "data" }); }, 1000); }; // Usage store.dispatch(myThunk);

Normal Action vs Thunk Function
Normal ActionThunk Function
// Normal Action Object const action = { type: "INCREMENT", payload: 1 }; // Usage store.dispatch(action);
// Thunk Function const myThunk = (dispatch, getState) => { setTimeout(() => { dispatch({ type: "INCREMENT", payload: 1 }); }, 1000); }; // Usage store.dispatch(myThunk);
SynchronousAsynchronous
📦 Plain Object🔧 Function
🎯 Direct to Reducer🔄 Via Middleware

Normal Action: { type: "ACTION_TYPE", payload: data }
Thunk Function: (dispatch, getState) => { /* async code */ }


Data Flow

Thunk function দিয়ে API calls, timers, এবং complex async logic সহজেই handle করা যায়।

কোড
store.js
const { createStore, applyMiddleware } = require("redux"); const { delayActionMiddleware, fetchAsyncMiddleware, } = require("./middlewares"); const { fetchTodos } = require("./functions"); // ধাপ-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(delayActionMiddleware, fetchAsyncMiddleware) ); // 5.a subscribe() এবং // 5.b getState() store.subscribe(() => { console.log(store.getState()); }); // 5.c dispatch() - Thunk Function dispatch করা store.dispatch(fetchTodos); // Sync Action (commented) // store.dispatch({ // type: "todos/todoLoaded", // payload: "Learn Redux from LWS", // });
store.dispatch(fetchTodos) - এখানে function dispatch করা হচ্ছে, object নয়।

Last updated on