should only depend on their state and action arguments
Pro or Con – multiple reducers can “fire” when a commonly named action is dispatched
Name a strategy for preventing the above
Using switch
By itself, a Redux store doesn’t know anything about async logic. It only knows how to synchronously dispatch actions, update the state by calling the root reducer function, and notify the UI that something has changed. Any asynchronicity has to happen outside the store.
Let’s look at a couple examples of how middleware can enable us to write some kind of async logic that interacts with the Redux store.
One possibility is writing a middleware that looks for specific action types, and runs async logic when it sees those actions, like these examples:
import { client } from '../api/client'
const delayedActionMiddleware = storeAPI => next => action => {
if (action.type === 'todos/todoAdded') {
setTimeout(() => {
// Delay this action by one second
next(action)
}, 1000)
return
}
return next(action)
}
const fetchTodosMiddleware = storeAPI => next => action => {
if (action.type === 'todos/fetchTodos') {
// Make an API call to fetch todos from the server
client.get('todos').then(todos => {
// Dispatch an action with the todos we received
dispatch({ type: 'todos/todosLoaded', payload: todos })
})
}
return next(action)
}
Thunk is a programming concept where a function is used to delay the evaluation/calculation of an operation.