> For the complete documentation index, see [llms.txt](https://easonwang.gitbook.io/web_advance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://easonwang.gitbook.io/web_advance/redux/redux-sagas.md).

# Redux sagas

## Redux sagas

<https://github.com/redux-saga/redux-saga>

簡介: 在action要放異步動作時，一般Redux的action會錯誤，所以只能用thunk或saga的方法

而saga的概念是監聽action，然後監聽到了之後執行相對應的邏輯，使用ES6 gererator的概念

> 注意: 如果使用saga的put之類的用法但不在generator function內的話可能會錯誤

1.一個按鈕點擊後發出一個普通action

```javascript
<div onClick={() => userLoginEnter()} />

userLoginEnter() {
    this.props.userLoginEnterAction({
      password: this.state.pass,
      groupId: this.state.gid,
      userId: this.state.name
    });  
}
```

2.該action與reducer

```javascript
export function userLoginEnter(payload) {
  return {
    payload,
    type: USER_LOGIN_ENTER
  };
}
```

reducer

```javascript
function loginPageReducer(state = initialState, action) {
  switch (action.type) {
  case USER_LOGIN_ENTER:
    return state.set('login', true);
  case USER_LOGIN:
    sessionStorage.setItem(sessionConst.userInfo, JSON.stringify(action.data));
    return state.set('userInfo', action.data);
  default:
    return state;
  }
}
```

最後寫sagas 的function與 watcher

```javascript
export function* userLoginEnter(action) {
  try {
    const payload = yield new Promise(resolve => {
      callApi('post', 'login', {
        password: action.payload.password,
        groupId: action.payload.groupId,
        userId: action.payload.userId,
        simpleLogin: false,
        appId: "we6"
      }, (response) => { resolve(response); });
    });
    yield put(userLogin(payload));
  } catch (err) {
    console.error(`userLogin saga error, err msg => ${err}`);
  }
}


export function* watchUserLogin() {
  yield takeLatest(USER_LOGIN_ENTER, userLoginEnter);
}

export default [
  watchUserLogin
];
```

記得要在store.js run

```javascript
sagaMiddleware.run(watchUserLogin);
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://easonwang.gitbook.io/web_advance/redux/redux-sagas.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
