реагировать родной - как сохранить данные с sqlite? потому что получил ошибку - PullRequest
0 голосов
/ 22 апреля 2020

Я хочу сохранить поля данных из axios, и мне нужно сделать это с SQLite, но получил предупреждение. есть способ решить это?

в моем случае я получил это, когда я печатаю (dbResult):

Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}
Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}
Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}
Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}
Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}

[Unhandled promise rejection: Error: near "Swift": syntax error (code 1 SQLITE_ERROR[1]): , while compiling: INSERT INTO places (artist, image, title, url) VALUES (Taylor Swift, https://images-na.ssl-images-amazon.com/images/I/61McsadO1OL.jpg, Taylor Swift, https://www.amazon.com/Taylor-Swift/dp/B0014I4KH6);]
- node_modules\expo-sqlite\build\SQLite.js:36:15 in _deserializeResultSet
* [native code]:null in map
- node_modules\expo-sqlite\build\SQLite.js:16:40 in SQLiteDatabase#exec
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in invokeCallbackAndReturnFlushedQueue

здесь я создаю базу данных и столбцы:

import * as SQLite from "expo-sqlite";

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

export const init = () => {
  const promise = new Promise((resolve, reject) => {
    db.transaction(tx => {
      tx.executeSql(
        'CREATE TABLE IF NOT EXISTS places (id INTEGER PRIMARY KEY NOT NULL, artist TEXT NOT NULL, image TEXT NOT NULL, title TEXT NOT NULL, url TEXT NOT NULL);',
        [],
        () => {
          resolve();
        },
        (_, err) => {
          reject(err);
        }
      );
    });
  });
  return promise;
};

export const insertPlace = (artist, image, title, url) => {
    const promise = new Promise((resolve, reject) => {
        db.transaction(tx => {
          tx.executeSql(
            `INSERT INTO places (artist, image ,title, url) VALUES (${artist}, ${image}, ${title}, ${url});`,
            [],
            (_, result) => {
              resolve(result);
            },
            (_, err) => {
              reject(err);
            }
          );
        });
      });
      return promise;
};

export const fetchPlaces = () => {
    const promise = new Promise((resolve, reject) => {
        db.transaction(tx => {
          tx.executeSql(
            'SELECT * FROM places',
            [],
            (_, result) => {
              resolve(result);
            },
            (_, err) => {
              reject(err);
            }
          );
        });
      });
      return promise;
};

и здесь я использую axios.get для получения данных и после использования функции insertPlace для сохранения данных полей в столбцы, которые в places.db я создал, но получил ошибку, как я упоминал и я не понимаю мою проблему там.


import axios from "axios";
import { insertPlace } from "../helpers/db";

export default class WaterQualitySamplesScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  getData = () => {
    axios
      .get("https://rallycoding.herokuapp.com/api/music_albums")
      .then((res) => {
        this.setState({
          data: res.data,
        });
        //  console.log(res.data);
        for (let i = 0; i < res.data.length; i++) {
          const mediaData = res.data[i];

            const dbResult =  insertPlace(
              mediaData.artist,
              mediaData.image,
              mediaData.title,
              mediaData.url
            );
            console.log(dbResult);

        }
      });
  };

async componentDidMount() {
    this.currentUser = await firebase.auth().currentUser;
    await this.registerForPushNotificationsAsync();

    this.getData();
  }

render() {
    return (
    ),
  };
};

Ответы [ 2 ]

0 голосов
/ 22 апреля 2020

Вы получаете ошибку здесь, потому что вы не awaiting последующее json() обещание после того, как начальное обещание разрешено.

Либо вы можете связать его с помощью then, либо вы можете использовать await, что более чище.

this.state = {
  data: "",
  isLoaded: false,
};

getData = async () => {
  try {
    const response = await fetch(
      "https://rallycoding.herokuapp.com/api/music_albums"
    );
    const jsonResponse = await response.json();
    console.log("jsonresponse0", jsonResponse);
    this.setState({ data: jsonResponse, isLoaded: true });
    this.saveDbData();
  } catch (error) {
    console.log(error);
  }
};

saveDbData = async () => {
  const { data, isLoaded } = this.state;
  if (isLoaded) {
    for (let i = 0; i < data.length; i++) {
      const mediaData = data[i];
      console.log(mediaData);
      const dbResult = await insertPlace(
        mediaData.artist,
        mediaData.image,
        mediaData.title,
        mediaData.url
      );
      console.log(dbResult);
    }
  }
};

0 голосов
/ 22 апреля 2020
  getData = () => {
    axios
      .get("https://rallycoding.herokuapp.com/api/music_albums")
      .then((res) => {
        this.setState({
          data: res.data,
        });
        //  console.log(res.data);
        for (let i = 0; i < res.data.length; i++) {
          const mediaData = res.data[i];

            const dbResult =  insertPlace(
              mediaData.artist,
              mediaData.image,
              mediaData.title,
              mediaData.url
            );
            console.log(dbResult);

        }
      })
     .catch(err => console.log(err))          // this is the catch
  };

Также может быть, что .then () отсутствует для решения проблемы.

...