Reputation: 47
Is possible to make an SQLite request async in Redux? The implementation from the documentation isn't async because dispatch(onLoading(false))
is fired before all DB inserts.
Action
const saveData = async () => {
await dispatch(onLoading(true));
await dispatch(saveSQL('DROP TABLE "bepr_problematiky"'));
await dispatch(
saveSQL(
'CREATE TABLE "bepr_problematiky" ( "id" integer NOT NULL, "uid" integer DEFAULT NULL, "title" varchar(255) NOT NULL, "text" text NOT NULL, "file" varchar(255) NOT NULL );'
)
);
for (const insert of inserts) {
await dispatch(
saveProblematiky(
`INSERT INTO 'bepr_problematiky' VALUES(${insert.id}, ${insert.uid}, '${insert.title}', '${insert.text}', '${insert.file}');`
)
);
}
return await dispatch(onLoading(false));
};
Component
export const saveSQL = (sql: string) => {
return async (dispatch: Dispatch<ProblematikyInterface>) => {
await db.transaction(async (tx) => {
await tx.executeSql(sql, [], (tx, results) => {
dispatch({
type: 'LOAD_PROBLEMATIKY',
payload: []
});
console.log('Saved');
});
});
};
};
Upvotes: 2
Views: 1685
Reputation: 476
If you are using SQLite for react native, I would recommend this WatermelonDB https://nozbe.github.io/WatermelonDB/ as it is a library built on SQLite and has many other features.
As in for your questions - If I am not mistaken, you would like to have an await your insert db call inside a function so that you can manipulate the loading condition for your UI state right?
I believe you can use redux-thunk for this as it resolve the async actions for redux. https://redux.js.org/tutorials/essentials/part-2-app-structure#writing-async-logic-with-thunks (this example is using redux-toolkit)
I hope it helps. If you already have the answer for this, do share it out as well. Thanks 🙏. Cheers !!
Upvotes: 2