使用Redux-Saga如何保存我的身份验证令牌?

时间:2018-03-19 01:52:07

标签: reactjs react-native redux redux-saga

我在React Native应用程序中使用Redux-Saga。当我从服务器获取身份验证令牌时,如何将其保存到本地存储?

我尝试使用

await AsyncStorage.setItem("token", token);

但React Native抱怨并说await是一个保留词。

我误解了什么吗?传奇代码不是我应该这样做的吗?

这是我的代码

function* loginFlow(action) {
  try {
    let username = action.username;
    let password = action.password;

    const response = yield call(getUser, username, password);
    let token = response.headers.get("access-token");

    const result = yield response.json();

    if (token) {
      console.log("success: ", token);

      yield put({ type: LOGIN_SUCCESS, result });
    } else {
      if (result.error) {
        yield put({ type: LOGIN_FAILURE, error: result.error });
      }
    }
  } catch (e) {
    yield put({ type: LOGIN_FAILURE, error: e.message });
    console.log("error", e);
  }
}

修改 这是getUser函数:

const getUser = (username, password) => {
  return fetch(`${apiURL}/${apiVersion}/${apiType}/${apiEndpoint_auth}`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      email: username,
      password: password
    })
  });
};

4 个答案:

答案 0 :(得分:1)

这是我设法将令牌存储在redux-saga生成器中的方式。

function* loginFlow(email, password) {
  try {
    // get your token
    const token = yield call(loginApi, email, password);

    // store token to local storage
    yield call(storeToken, token);

    yield put({ type: LOGIN_SUCCESS });

  } catch (error) {
    yield put({ type: LOGIN_ERROR, error });
  }
}

function loginApi(email, password) {
  return fetch('https://yourApiUrl', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ email, password }),
  })
    .then(response => response.json())
    .then(json => json)
    .catch((error) => {
      throw error;
    });
}

async function storeToken(token) {
      try {
        await AsyncStorage.setItem('token', token);
      } catch (error) {
        console.log('AsyncStorage error during token store:', error);
      }
    }

注意:在调度LOGIN_SUCCESS操作之前,请存储您的令牌。这样,您就可以通过LOGIC_SUCCESS操作进行的重新渲染来在React Component中获得令牌。

答案 1 :(得分:0)

  

请记住,await关键字仅在异步函数中有效。如果你在异步函数体之外使用它,你将得到一个SyntaxError。

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

函数生成器需要在 function 之前有 async

答案 2 :(得分:0)

由于AsyncStorage API的每个方法都返回一个Promise对象,您可以这样做:

function* loginFlow(action) {
  try {
    let username = action.username;
    let password = action.password;

    const response = yield call(getUser, username, password);
    let token = response.headers.get("access-token");

    const result = yield response.json();

    if (token) {
      console.log("success: ", token);

      // This is a blocking call that would wait for the token to be stored,
      // or for the Promise to be resolved before proceeding to the next line
      yield call(AsyncStorage.setItem, "token", token);

      yield put({ type: LOGIN_SUCCESS, result });
    } else {
      if (result.error) {
        yield put({ type: LOGIN_FAILURE, error: result.error });
      }
    }
  } catch (e) {
    yield put({ type: LOGIN_FAILURE, error: e.message });
    console.log("error", e);
  }
}

希望这有帮助。

答案 3 :(得分:0)

在以下功能中传递您的身份验证令牌。

  saveToken = async (token) => {
    try {

      AsyncStorage.setItem("token", "" + token);

    } catch (error) {
      console.log('AsyncStorage error: ' + error.message);
    }
  }