Home > OS >  retrieving data from an api call
retrieving data from an api call

Time:11-24

I have successfully retrieved data from a login API call and I return the data variable which logs user information eg. id, token, email and this is successfully printed to the console.

async function login(email: string, password: string, rememberMe: boolean) {
  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password, rememberMe }),
  };

  await fetch(`${API_URL}/auth/login`, requestOptions).then((response) => {
    if (response.ok === true) {
      response.json().then((data) => {
        console.log(data);
        if (data.success === true) {
          localStorage.setItem("USER_ID", data.id);
          localStorage.setItem("EMAIL", data.email);
          localStorage.setItem("ACCESS_TOKEN_KEY", data.token);
          return data;
        } else {
          return Promise.reject(new Error("toast.user.general_error"));
        }
      });
    } else {
      return Promise.reject(new Error(response.statusText));
    }
  });
}

however I get user = undefined when logging to the console suggesting that my data variable is undefined

function login(email: string, password: string, rememberMe: boolean) {
  return (dispatch: ThunkDispatch<{}, void, AnyAction>) => {

    authService.login(email, password, rememberMe).then(
      (user) => {
        history.push("/student/dashboard");
        console.log("user = ", user);
      },
      (error) => {
        dispatch(failure(error.toString()));
      }
    );
  };
}

why am I not retrieving the user variable from my fetch request? Should I be wrapping the data variable with a promise before returning it?

CodePudding user response:

Login must return something at the top-level, not from within a then block. Since you're already using async/await, try it like this.

async function login(email: string, password: string, rememberMe: boolean) {
  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password, rememberMe }),
  };

  const response = await fetch(`${API_URL}/auth/login`, requestOptions);
  
  if (!response.ok) return new Error(response.statusText);

  const data = await response.json();
  console.log(data);
  if (data.success !== true) return new Error("toast.user.general_error");
  return data;
}
  • Related