Using 'take' and 'put' Effects to Handle Actions
Showcase a Redux-Saga middleware function using 'take' to listen for a specific action and 'put' to dispatch a new action in response, illustrating the flow of controlling side effects.
import { put, take } from 'redux-saga/effects';
function* loginUserSaga() {
// Wait for the LOGIN_REQUEST action to be dispatched
const action = yield take('LOGIN_REQUEST');
try {
// Simulate a login API call
const user = { id: 1, name: 'Alice' };
// Dispatch LOGIN_SUCCESS action with the user data
yield put({ type: 'LOGIN_SUCCESS', user });
} catch (error) {
// If error, dispatch LOGIN_FAILURE action
yield put({ type: 'LOGIN_FAILURE', error });
}
}
This saga waits for a LOGIN_REQUEST action. Once it receives that action, it simulates a user login, then dispatches either a LOGIN_SUCCESS action with the user's data if the login is successful, or a LOGIN_FAILURE action with the error if there's a failure. This showcases using 'take' to listen for actions and 'put' to dispatch new actions.