Exploring Realm and MongoDB for the first time has been an interesting journey for me. I began by following a helpful tutorial as a starting point for my project.
Here is the link to my project structure on CodeSandbox
The folder structure includes:
src
|_ components
|_ pages
|_ Authentication.tsx
|_ Home.tsx
|_ Logout.tsx
|_ App.tsx
|_ Navigation.tsx
|_ RestaurantCard.tsx
|_ lib
|_ db-utils.ts
|_ state
|_ index.ts
|_ DbModel.ts
I will only be sharing snippets of some easily understandable components here.
Snippet from App.tsx:
const serviceName = "mongodb-atlas";
export function App() {
return (
<Provider value={stateInstance}>
<AppWithState />
</Provider>
);
}
function AppWithState() {
const {
db: { app, client, setClient, user, setUser }
} = useMst();
useEffect(() => {
async function init() {
if (!user) {
const credentials = Realm.Credentials.anonymous();
const newUser = app.currentUser
? app.currentUser
: await app.logIn(credentials);
setUser(newUser);
}
if (!client) {
const newClient = app.currentUser.mongoClient(serviceName);
setClient(newClient);
}
}
init();
}, [app, client, user]);
return (
<Router>
<Navigation />
<Switch>
<Route path="/"" component={Home} /">
...
</Switch>
</Router>
);
}
Code snippet from state/index.ts:
...
Code snippet from state/DbModel.ts:
...
Snippet from Home.tsx:
...
Snippet from Authentication.tsx:
...
In my implementation, I opted for MobX state tree instead of using React context like the tutorial author did. The code setup involves working with a sample database of restaurants. One particular challenge I encountered was getting stuck at the Home
component where the data retrieval seemed unproductive due to client
and user
being null. Despite setting them up in the App
component and saving them in the state, I couldn't pinpoint the issue causing the deadlock.
Additionally, there were instances where an error message stating
Cannot assign to read-only property '_locationUrl' of object '#<App>'
appeared, leaving me perplexed about its origin and resolution.
Upon cloning the repository created by the tutorial author and observing it functioning correctly, I am left wondering what could potentially be wrong with my own code. It seems to hint towards a problem related to Promises, but tackling it remains uncertain.