Ben Aston
Ben Aston

Reputation: 55729

Waiting in a redux-saga

I want to introduce a delay in a saga (using redux-saga).

How can I do this?

If redux-saga provides an API, I would also be interested in how to achieve it manually.

function* save({ payload }) {
    yield put(pending());
    // I want to simply wait (non-blocking) here for say 2 seconds
    yield put(complete());
}

Upvotes: 16

Views: 22756

Answers (4)

Elyes Ben khoud
Elyes Ben khoud

Reputation: 11

Using delay as imported from redux-saga/effects would solve your issue in one line

Upvotes: 0

NullDev
NullDev

Reputation: 7303

You could achieve that with a promise and a generator function:

function sleep(sec) { 
    return new Promise(resolve => setTimeout(resolve, sec*1000)); 
}

function* save({ payload }) {
    yield put(pending());
    yield sleep(2); //wait 2 seconds
    yield put(complete());
}

Upvotes: 3

Cleiton
Cleiton

Reputation: 18113

Redux-sagas has a special effect for this:

delay(ms, [val])

Returns a Promise that will resolve after ms milliseconds with val.

Example:

import { delay, call } from 'redux-saga/effects'

function* someSaga(input) {
  yield put(someAction())
  yield delay(500)
  yield put(anotherAction())
}

Upvotes: 41

Ben Aston
Ben Aston

Reputation: 55729

Source.

export function delay(ms, val = true) {
  let timeoutId
  const promise = new Promise(resolve => {
    timeoutId = setTimeout(() => resolve(val), ms)
  })

  promise[CANCEL] = () => clearTimeout(timeoutId)

  return promise
}

Upvotes: 0

Related Questions