Skip to Content
🤖 Technology
Redux
7. Raw Async Actions

Raw Intro to Asynchronous Actions

Redux এ async operations করার জন্য middleware ব্যবহার করতে হয়। Middleware async action কে actual action এ convert করে।


Redux Async Data Flow
store.js
const { createStore, applyMiddleware } = require("redux"); const {delayActionMiddleware,fetchTodosMiddleware,} = require("./middlewares"); // ধাপ-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, fetchTodosMiddleware)); // 5.a subscribe() এবং // 5.b getState() store.subscribe(() => { console.log(store.getState()); }); // 5.c dispatch() // store.dispatch({ // type: "todos/todoLoaded", // payload: "Learn Redux from LWS", // }); store.dispatch({ type: "todos/fetchTodos", });
middlewares.js
const { default: fetch } = require("node-fetch"); const delayActionMiddleware = (store) => (next) => (action) => { if (action.type === "todos/todoLoaded") { console.log("I am delaying you!"); setTimeout(() => { next(action); }, 3000); return; } return next(action); }; const fetchTodosMiddleware = (store) => (next) => async (action) => { if (action.type === "todos/fetchTodos") { const response = await fetch( "https://jsonplaceholder.typicode.com/todos?_limit=5" ); const todos = await response.json(); store.dispatch({ type: "todos/todoLoaded", payload: todos, }); console.log(`Number of updates todos: ${store.getState().todos.length}`); return; } return next(action); }; module.exports = {delayActionMiddleware,fetchTodosMiddleware,};
Last updated on