Ionic React Sqlite

I delve into integrating the Capacitor SQLite plugin with Ionic and React. I share my experience with the plugin’s documentation and sample applications and explain why I used simple API calls instead of React hooks. I also provide insights into the installation process, including using the Ionic Visual Studio Code plugin and copying the SQL Wasm file. If you’re interested in making the plugin work on the web, I also cover that topic. So, join me as we explore the ins and outs of integrating the Capacitor SQLite plugin with Ionic and React! Don’t forget to like, subscribe, and let’s get started!

4 Likes
  const loadData = async () => {
    try {
      // query db
      performSQLAction(async (db: SQLiteDBConnection | undefined) => {
        const respSelect = await db?.query(`SELECT * FROM test`);
        setItems(respSelect?.values);
        // Not working log:
        console.log(`items:`, {items});

If I log the items now, it shows me “empty”. But that’s not true. The log seems to be set to early.
How can I log the items correctly after the await for the query?

You could add a useEffects that has a dependency on the state variable, when the update is completed it will trigger the useEffect to log the change

1 Like

Thank you for this answer, it works!

But I’ve got a problem, if I want to load Data and want to use this data directly afterwards. Do you have a hint for this as well? Even if I use Promis.all it sets too early and so to an empty array.

useEffect(() => {
  const fetchData = async () => {
    const fetchDataPromises = [
      loadData()
    ];
    await Promise.all(fetchDataPromises);  
    setNewListItems([...items]);
  }
  
fetchData();
}, [appDataReady]);

react-query and suspense is great for this. I am loading data from a database all over my app, and setting up useEffect all the time is really a pain.

react-query makes it easy to load data and cache it intelligently. The useQuery() hook has statuses like isLoading isPending and so on, which make it easy to work with.

1 Like