Blog>
Snippets

Updating State with put Effect

Demonstrate using the `put` effect to dispatch an action to the Redux store, updating the application state after performing a side effect.
import { put } from 'redux-saga/effects';
import { updateSuccess } from './actionCreators';

// Example of a saga worker performing a side effect and then updating the state
function* updateDataSaga(action) {
    try {
        // Perform side effect (E.g., fetching data, calculations)
        const newData = action.payload; // Assuming payload contains new data
        // Dispatch an action to update the state in the store
        yield put(updateSuccess(newData));
    } catch (error) {
        console.error('Error updating data:', error);
        // You might dispatch a failure action here with 'yield put'
    }
}
This code snippet demonstrates how to use the `put` effect within a Redux-Saga worker to update the application state by dispatching an action. Here, `updateSuccess` is an action creator that returns an action object which is dispatched to the store using `put`. The `updateDataSaga` function is triggered by some action, performs a side effect (like fetching or processing data), and then dispatches an `updateSuccess` action with the new data to update the state.