1

In my react project, I have the following code.

import uuid from 'uuid';
import { SET_ALERT, REMOVE_ALERT } from './types';

export const setAlert = (msg, alertType, timeout = 5000) => dispatch => {
  const id = uuid.v4();
  dispatch({
    type: SET_ALERT,
    payload: { msg, alertType, id }
  });

  setTimeout(() => dispatch({ type: REMOVE_ALERT, payload: id }), timeout);
};

Here thunk has been used. Im applying saga into the project and I want to rewrite with saga. Since there is no API calls, i dont want to send through via a saga to the reducer. I want to go to the reducer from this action directly. So how can I rewrite without dispatch?

1 Answer 1

5

Sagas are to used to handle side-effects, You can use put to dispatch an action directly from your saga.

Here's an example from redux-saga official docs

import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import Api from '...'

// worker Saga: will be fired on USER_FETCH_REQUESTED actions
function* fetchUser(action) {
   try {
      const user = yield call(Api.fetchUser, action.payload.userId);
      yield put({type: "USER_FETCH_SUCCEEDED", user: user});
   } catch (e) {
      yield put({type: "USER_FETCH_FAILED", message: e.message});
   }
}

so If I am to write your code it will be something like this:

import uuid from 'uuid';
import { SET_ALERT, REMOVE_ALERT } from './types';
import { put } from 'redux-saga/effects'

export const setAlert = (msg, alertType, timeout = 5000) => {
  const id = uuid.v4();
  put({
    type: SET_ALERT,
    payload: { msg, alertType, id }
  });

  setTimeout(() => put({ type: REMOVE_ALERT, payload: id }), timeout);
};

In your worker saga:

function* someAction(action) {
  try {
     // some logic
     yield setAlert(msg, 5000);
  } catch (e) {
     // some error handling logic
  }
}

I have not tested it, however it should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.