The MongoDB Realm Web SDK enables browser-based applications to access data stored in MongoDB Atlas and interact with MongoDB Realm services like Functions and authentication. The Web SDK supports both JavaScript and TypeScript applications.
In this short video we are refactoring application state related to Realm and Mongodb into a separate composition function instead of using something like vuex for state manager. We start with the code from the previous video
Currently, there is no solution for writing to the local database as a replacement for sqlite in an Ionic Application. It looks like some people have started to build a plugin, but didn't get too far.
We are building the application using Vuejs, it is being packaged and developed using ViteJS and the UI Components are from Ionic Framework
// realm-state.ts
import * as Realm from "realm-web";
import { computed, ref } from "vue";
const user = ref<any>(null);
// get app instance
const app = Realm.getApp("application-vue-1-afmqh");
user.value = app?.currentUser;
export const useAppState = () => {
const isLoggedIn = computed(() => user.value !== null);
/**
*
*/
const login = async (email: string, password: string) => {
const credentials = Realm.Credentials.emailPassword(email, password);
await app.logIn(credentials);
// Refresh a user's custom data to make sure we have the
// latest version
await app?.currentUser?.refreshCustomData();
//assign logged in user
user.value = app?.currentUser;
return true;
};
/**
*
* @returns
*/
const logout = async () => {
await app.currentUser?.logOut();
//assign logged in user
user.value = null;
return true;
};
const createAccount = async ({
email,
password,
first,
last,
}: {
email: string;
password: string;
first: string;
last: string;
}) => {
// Create user
await app.emailPasswordAuth.registerUser(email, password);
// Authenticate the user
await app.logIn(Realm.Credentials.emailPassword(email, password));
// save profile information
const mongodb = app?.currentUser?.mongoClient("mongodb-atlas");
const collection = mongodb?.db("vue-db1").collection("profile");
const resp = await collection?.insertOne({
userID: app?.currentUser?.id,
first,
last,
});
// Refresh a user's custom data to make sure we have the latest version
await app?.currentUser?.refreshCustomData();
//assign logged in user
user.value = app?.currentUser;
return app.currentUser;
};
return {
isLoggedIn,
user,
// functions
login,
logout,
createAccount,
};
};
Top comments (0)