使用redux-saga调用异步api

时间:2022-12-28 10:59:14

I am following redux-saga documentation on helpers, and so far it seems pretty straight forward, however I stumbled upon an issue when it comes to performing an api call (as you will see link to the docs points to such example)

我正在关注有关帮助程序的redux-saga文档,到目前为止看起来很简单,但是在执行api调用时我偶然发现了一个问题(因为你会看到文档的链接指向这样的例子)

There is a part Api.fetchUser that is not explained, thus I don't quiet understand if that is something we need to handle with libraries like axios or superagent? or is that something else. And are saga effects like call, put etc.. equivalents of get, post? if so, why are they named that way? Essentially I am trying to figure out a correct way to perform a simple post call to my api at url example.com/sessions and pass it data like { email: 'email', password: 'password' }

有一部分Api.fetchUser未解释,因此我不清楚是否需要处理像axios或superagent这样的库?还是那个别的东西。并且是传奇效果,如电话,放等等。获得,等等?如果是这样,为什么他们这样命名?基本上我正在尝试找出一个正确的方法,在url example.com/sessions上对我的api执行一个简单的帖子调用,并将其传递给{email:'email',密码:'password'}

2 个解决方案

#1


35  

Api.fetchUser is a function, where should be performed api ajax call and it should return promise.

Api.fetchUser是一个函数,应该执行api ajax调用,它应该返回promise。

In your case, this promise should resolve user data variable.

在您的情况下,此承诺应解析用户数据变量。

For example:

例如:

// services/api.js
export function fetchUser(userId) {
  // `axios` function returns promise, you can use any ajax lib, which can
  // return promise, or wrap in promise ajax call
  return axios.get('/api/user/' + userId);
};

Then is sagas:

然后是传奇:

function* fetchUserSaga(action) {
  // `call` function accepts rest arguments, which will be passed to `api.fetchUser` function.
  // Instructing middleware to call promise, it resolved value will be assigned to `userData` variable
  const userData = yield call(api.fetchUser, action.userId);
  // Instructing middleware to dispatch corresponding action.
  yield put({
    type: 'FETCH_USER_SUCCESS',
    userData
  });
}

call, put are effects creators functions. They not have something familiar with GET or POST requests.

call,put是效果创建者的功能。他们没有熟悉GET或POST请求的东西。

call function is used to create effect description, which instructs middleware to call the promise. put function creates effect, in which instructs middleware to dispatch an action to the store.

call函数用于创建效果描述,指示中间件调用promise。 put函数创建效果,指示中间件将操作分派给商店。

#2


4  

Things like call, put, take, race are effects creator functions. The Api.fetchUser is a placeholder for your own function that handles API requests.

像call,put,take,race这样的东西是效果创建者的功能。 Api.fetchUser是您自己的函数的占位符,用于处理API请求。

Here’s a full example of a loginSaga:

这是loginSaga的完整示例:

export function* loginUserSaga() {
  while (true) {
    const watcher = yield race({
      loginUser: take(USER_LOGIN),
      stop: take(LOCATION_CHANGE),
    });

    if (watcher.stop) break;

    const {loginUser} = watcher || {};
    const {username, password} = loginUser || {};
    const data = {username, password};

    const login = yield call(SessionService.login, data);

    if (login.err === undefined || login.err === null && login.response) {
      yield put(loginSuccess(login.response));
    } else {
      yield put(loginError({message: 'Invalid credentials. Please try again.'}));
    }
  }
}

In this snippet, the SessionService is a class that implements a login method which handles the HTTP request to the API. The redux-saga call will call this method and apply the data parameter to it. In the snippet above, we can then evaluate the result of the call and dispatch loginSuccess or loginError actions accordingly using put.

在此片段中,SessionService是一个实现登录方法的类,该方法处理对API的HTTP请求。 redux-saga调用将调用此方法并将data参数应用于该方法。在上面的代码片段中,我们可以使用put来评估调用的结果并相应地调度loginSuccess或loginError操作。

A side note: The snippet above is a loginSaga that continuously listens for the USER_LOGIN event, but breaks when a LOCATION_CHANGE happens. This is thanks to the race effect creator.

旁注:上面的代码片段是一个持续监听USER_LOGIN事件的loginSaga,但是当LOCATION_CHANGE发生时会中断。这要归功于种族效应创造者。

#1


35  

Api.fetchUser is a function, where should be performed api ajax call and it should return promise.

Api.fetchUser是一个函数,应该执行api ajax调用,它应该返回promise。

In your case, this promise should resolve user data variable.

在您的情况下,此承诺应解析用户数据变量。

For example:

例如:

// services/api.js
export function fetchUser(userId) {
  // `axios` function returns promise, you can use any ajax lib, which can
  // return promise, or wrap in promise ajax call
  return axios.get('/api/user/' + userId);
};

Then is sagas:

然后是传奇:

function* fetchUserSaga(action) {
  // `call` function accepts rest arguments, which will be passed to `api.fetchUser` function.
  // Instructing middleware to call promise, it resolved value will be assigned to `userData` variable
  const userData = yield call(api.fetchUser, action.userId);
  // Instructing middleware to dispatch corresponding action.
  yield put({
    type: 'FETCH_USER_SUCCESS',
    userData
  });
}

call, put are effects creators functions. They not have something familiar with GET or POST requests.

call,put是效果创建者的功能。他们没有熟悉GET或POST请求的东西。

call function is used to create effect description, which instructs middleware to call the promise. put function creates effect, in which instructs middleware to dispatch an action to the store.

call函数用于创建效果描述,指示中间件调用promise。 put函数创建效果,指示中间件将操作分派给商店。

#2


4  

Things like call, put, take, race are effects creator functions. The Api.fetchUser is a placeholder for your own function that handles API requests.

像call,put,take,race这样的东西是效果创建者的功能。 Api.fetchUser是您自己的函数的占位符,用于处理API请求。

Here’s a full example of a loginSaga:

这是loginSaga的完整示例:

export function* loginUserSaga() {
  while (true) {
    const watcher = yield race({
      loginUser: take(USER_LOGIN),
      stop: take(LOCATION_CHANGE),
    });

    if (watcher.stop) break;

    const {loginUser} = watcher || {};
    const {username, password} = loginUser || {};
    const data = {username, password};

    const login = yield call(SessionService.login, data);

    if (login.err === undefined || login.err === null && login.response) {
      yield put(loginSuccess(login.response));
    } else {
      yield put(loginError({message: 'Invalid credentials. Please try again.'}));
    }
  }
}

In this snippet, the SessionService is a class that implements a login method which handles the HTTP request to the API. The redux-saga call will call this method and apply the data parameter to it. In the snippet above, we can then evaluate the result of the call and dispatch loginSuccess or loginError actions accordingly using put.

在此片段中,SessionService是一个实现登录方法的类,该方法处理对API的HTTP请求。 redux-saga调用将调用此方法并将data参数应用于该方法。在上面的代码片段中,我们可以使用put来评估调用的结果并相应地调度loginSuccess或loginError操作。

A side note: The snippet above is a loginSaga that continuously listens for the USER_LOGIN event, but breaks when a LOCATION_CHANGE happens. This is thanks to the race effect creator.

旁注:上面的代码片段是一个持续监听USER_LOGIN事件的loginSaga,但是当LOCATION_CHANGE发生时会中断。这要归功于种族效应创造者。