Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use async await inside redux saga?

I'm trying to use ES javascript api to get data from Elastic Search and show it in my React Redux Redux-Saga code.

function* getData() {
  const response = async () => await client.msearch({
     body: [
    // match all query, on all indices and types
    {},
    { query: { match_all: {} } },

    // query_string query, on index/mytype
    { index: 'myindex', type: 'mytype' },
    { query: { query_string: { query: '"Test 1"' } } },
  ],
  });

  yield put(Success({
    Data: response(),
  }));
}

The problem is I don't know how to make the yield wait for the response to be resolved. Is there any other way to use a promise inside redux saga and es javascript-client ?

like image 422
Etherealm Avatar asked Aug 21 '18 15:08

Etherealm


People also ask

How do I use async await in redux saga?

You should never be calling the await function directly inside the saga-generator, because redux-saga is for orchestrating the side-effects. Therefore, any time that you want to run a side-effect you should do it by yielding the side-effect through a redux-saga effect (usually: call or fork ).

Can we use async await in redux saga?

You can transpile async/await into generators, but you can't do the reverse. As a userland library, redux-saga can handle asynchronous behavior in ways that async/await doesn't.

Is redux saga asynchronous?

Redux Saga utilizes ES6 generator functions for this. Generators allow for synchronously written asynchronous code. A generator will automatically pause — or yield — at each asynchronous call until it completes before continuing.

Does redux saga use promises?

An action creator, createPromiseAction() that you can use to define actions which return promises. We call an action that returns a promise a promise action. Saga helpers implementPromiseAction() , resolvePromiseAction() , and rejectPromiseAction() that you use to resolve or reject a promise action's promise.


Video Answer


1 Answers

I figured it out. Putting the answer here for anyone looking for it.

function* getData(data) {
  const response = yield call(fetchSummary, data);
  yield put(Success({
    Data: response,
  }));
}

async function fetchSummary(data) {
  return await client.msearch({
     body: [
     // match all query, on all indices and types
     {},
     { query: { match_all: {} } },

     // query_string query, on index/mytype
     { index: 'myindex', type: 'mytype' },
     { query: { query_string: { query: data.query } } },
    ],
  });
}
like image 181
Etherealm Avatar answered Nov 15 '22 11:11

Etherealm