使用SQLite响应本地登录

cl25kdpy  于 2022-12-13  发布在  SQLite
关注(0)|答案(2)|浏览(134)

我创建了一个登录,我想把它的详细信息保存在SQLite上。这是我第一次使用SQLite,我也在学习React Native with Expo。我已经在App.ts上按照教程初始化了SQLite,它工作得很好,但是现在我不知道如何从这里移动。我用Firebase做了验证,它也工作得很好。这是我用redux做的auth.action页面:

import { URL_AUTH_API, URL_LOGIN_API } from "../../constants/dataBase";

export const SIGNUP = 'SIGNUP';
export const LOGIN = 'LOGIN';

export const signup = (name: string, email: string, password: string) => {
  return async (dispatch: any) => {
    const response = await fetch(URL_AUTH_API, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name,
        email,
        password,
        returnSecureToken: true,
      }),
    });

    if (!response.ok) {
      const errorResponse = await response.json();
      const errorID = errorResponse.error.message;

      let message = 'You could not sign up, please try again';
      if (errorID === 'EMAIL_EXISTS') message = 'This email is already register';

      throw new Error(message);
    }

    const data = await response.json();

    dispatch({
      type: SIGNUP,
      token: data.idToken,
      userId: data.localId,
    });
  }
}

export const login = (email: string, password: string) => {
  return async (dispatch: any) => {
    const response = await fetch(URL_LOGIN_API, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email,
        password,
        returnSecureToken: true,
      }),
    });

    if (!response.ok) {
      const errorResponse = await response.json();
      const errorID = errorResponse.error.message;

      let message = 'Can not log in';
      if (errorID === 'EMAIL_NOT_FOUND') message = 'We do not have this email in our data base';

      throw new Error(message);
    }

    const data = await response.json();

    dispatch({
      type: LOGIN,
      token: data.isToken,
      userId: data.localId,
    });
  }
}

这是数据库.ts:

import * as SQLite from 'expo-sqlite';

const db = SQLite.openDatabase('address.db');

export interface SQLTransaction {
    
    
}

export const init = () => {
    return new Promise<void>((resolve, reject) => {
        db.transaction((tx) => {
            tx.executeSql(`CREATE TABLE IF NOT EXISTS user (
                name TEXT NOT NULL,
                email TEXT NOT NULL,
                password TEXT NOT NULL
            )`,
            [],
            () => resolve(),
            (_, err): boolean | any => reject(err),
            )
        });
    });
}

export const userDetails = (name: string, email: string, password: string) => {
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            tx.executeSql(
                'INSERT INTO user (name, email, password) VALUES (?, ?, ?)',
                [name, email, password],
                (_, result) => resolve(result),
                (_, error): boolean | any => reject(error),
            )
        })
    })
}

export const fetchUser = () => {
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            tx.executeSql(
                'SELECT * FROM user',
                [],
                (_, result) => resolve(result),
                (_, error): boolean | any => reject(error),
            )
        })
    })
}

如果有人能帮助我,我非常感激。提前感谢。

i2loujxw

i2loujxw1#

我刚刚在注册组件中做了init函数,看起来它可以工作。另外,我在那里添加了fetchUser函数,以验证表是否已经创建,并在终端上显示它存在。
这是我在注册中添加的函数:

init()
    .then(() => data)
    .catch(err => {
      console.log('Database failed to connect');
      console.log(err.message);
    })

    fetchUser()
    .then(() => console.log('result fetchUser', name, email, password))
    .catch(err => {
      console.log('table not created yet');
      console.log(err.message);
    })
vngu2lb8

vngu2lb82#

如果以这种方式实现,它将起作用

import * as SQLite from 'expo-sqlite';

卿卿这才道:

try {
  mInit();
  // insertUserDetails("MMM","mEmail@gmail.com","Password123!@#")
  fetchUser();
} catch (e) {
  console.log("Database Error!");
  console.log(e);
}
const db = SQLite.openDatabase("address.db");
const mInit = () => {
  return new Promise<void>((resolve, reject) => {
    db.transaction((tx) => {
      tx.executeSql(
        `CREATE TABLE IF NOT EXISTS user (
              name TEXT NOT NULL,
              email TEXT NOT NULL,
              password TEXT NOT NULL
          )`,
        [],
        () => resolve(),
        (_, err): boolean | any => reject(err)
      );
    });
  });
};
const insertUserDetails = (name: string, email: string, password: string) => {
  return new Promise((resolve, reject) => {
    db.transaction((tx) => {
      tx.executeSql(
        "INSERT INTO user (name, email, password) VALUES (?, ?, ?)",
        [name, email, password],
        (_, result) => resolve(result),
        (_, error): boolean | any => reject(error)
      );
    });
  });
};
const fetchUser = () => {
  return new Promise((resolve, reject) => {
    db.transaction((tx) => {
      tx.executeSql(
        "SELECT * FROM user",
        [],
        (_, result) => {
          var temp = [];
          for (let i = 0; i < result.rows.length; ++i)
            temp.push(JSON.stringify(result.rows.item(i)));
          console.log("Result=>" + temp);
          console.log("Feched EVeerything" + result);
        },
        (_, error): boolean | any => reject(error)
      );
    });
  });
};
Result=>{"name":"MMM","email":"mEmail@gmail.com","password":"Password123!@#"},{"name":"MMM","email":"mEmail@gmail.com","password":"Password123!@#"},{"name":"MMM","email":"mEmail@gmail.com","password":"Password123!@#"}

相关问题