ReactNative×SQLiteのINSERTでハマった話

まずは結論から。

ReactNativeを使って、モバイル端末のローカルDB(SQLite)にインサートしようとするけど、なぜだか上手くデータが入らない。

その原因はtextカラムにハイフン付きの文字列を入れようといたからでした。

  // const createdAt: string = dayjs().format('YYYY-MM-DD HH:mm:ss');
  const createdAt: string = dayjs().format('YYYY-MM-DD');
  console.log(body, selectedTemplate, createdAt);
  db.transaction((tx:any) => {
    tx.executeSql(
      // 実行したいSQL文
      // ?のところに引数で設定した値が順番に入る
      `insert into diaries (body, emoji, feel_id, updated_at, created_at) values ('test', '1111', 1, 2022-02-22, 2022-02-22);`,
      // ↓これはOK
      //`insert into diaries (body, emoji, feel_id, updated_at, created_at) values ('test', '1111', 1, '2022-02-22', '2022-02-22');`,
      [],
      // 成功時のコールバック関数
      (sqlTxn, res) => {
        console.log(sqlTxn);
        console.log(`Diary added successfully`);
        console.log(res);
      },
      error => {
        console.log('ERROR');
        console.log(error);
        // return false;
      },
    )
  });
}

英語圏アプリで会社や嫌な取引先に依存しない収入を作りませんか?
その裏側を紹介するメールマガジンを配信しているので、ご興味あれば覗いてみてくださいね。