1

I am learning React and Typescript and following this tutorial (AWS Cognito + React JS Tutorial: Getting Sessions and Logging out (2020) [Cognito Episode #3] https://youtu.be/T7tXYHy0wKE). I am trying to call my new React Context with AccountContext.Provider but the default value is not working because there is a Promise in the function that is being used in the value field, but no Promise in the default value. Can I write something like this?

const AccountContext = createContext<UserAuthTypes>(username: '', password: '' => await new Promise);

I defined AccountContext to have the default value username: '', password: '', but I get this error in the return statement, on the value= line:

TS2739: Type '{ authenticate: (username: string, password: string) => Promise<unknown>; }' is missing the following properties from type 'UserAuthTypes': username, password 

I see that authenticate has username and password as the inputs and a Promise as the output.

The code which is based off of this tutorial: AWS Cognito + React JS Tutorial: Getting Sessions and Logging out (2020) [Cognito Episode #3] https://youtu.be/T7tXYHy0wKE):

export interface UserAuthTypes {
  username: string;
  password: string;
  authenticate?: any; 
}

export const initialUserAuthState = {
  username: '',
  password: '',
};

........

const AccountContext = createContext<UserAuthTypes>(initialUserAuthState);

const Account = (props: { children: ReactNode }) => {
  const authenticate = async (username: string, password: string) =>
    await new Promise((resolve, reject) => {
      const user = new CognitoUser({
        Username: username,
        Pool: UserPool,
      });

      const authDetails = new AuthenticationDetails({
        Username: username,
        Password: password,
      });

      user.authenticateUser(authDetails, {
        onSuccess: (data) => {
          resolve(data);
        },
        onFailure: (err) => {
          reject(err);
        },
        newPasswordRequired: (data) => {
          resolve(data);
        },
      });
    });
  return (
    <AccountContext.Provider value={{ authenticate }}>
      {props.children}
    </AccountContext.Provider>
  );
};

export { Account, AccountContext };

0 Answers0