Attempting to establish a connection with MongoDB through Realm

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.

Answer №1

Utilizing mobx-state-tree alongside the usage of types.frozen in DbModel.ts is causing interference with Realm.App. This issue arises because the MongoDB Realm code internally attempts to modify the Realm.App instance, which fails due to its frozen state.

To remedy this problem, relocate the creation of the Realm.App within your App's code. You can implement a solution similar to the following:

function AppWithState() {
  const {
    db: {   client, setClient, user, setUser }
  } = useMst();
  const [app] = useState(new Realm.App(appConfig)) // <-- Implement this fix and remove the instantiation of Realm.App from DbModel.ts
 
  .... Continue with the remaining parts of your AppWithState code .....
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to resolve the error 'content-type missing boundary' and encountering the issue with getBoundary not being recognized as a function?

fetchCarouselData: async (params) => { let bodyFormData = new FormData(); for (let prop in params) { bodyFormData.append(prop, params[prop]); } return axios({ method: "post", url: `${baseURL}/fetchCarouselData`, data: b ...

Does every controller page need to verify the Login Function?

In my PHP pages, I have implemented the MVC Pattern by creating a controller page for each view page to interact with the Model page. However, I have only checked user login at the top of every view page and not in the controller page. This leaves a potent ...

Inconsistent Animation Issue with jQuery Toggle for Expanding Div and Text

My expanding div functionality is almost perfect, but I've noticed that the transition when opening abruptly on divs with text. However, the closing transition is smooth. Can anyone help me make the opening transition as smooth as the closing one? Bel ...

Can anyone suggest a more efficient method for specifying the type of a collection of react components?

Picture this scenario: you are extracting data from an API and creating a list of Card components to be displayed in a parent component. Your code might resemble the following: function App() { let items = [] // How can I specify the type here to avoid ...

Adding multiple text as label and sublabel in a React MUI Tooltip can be achieved by utilizing the appropriate

I'm struggling to incorporate a MaterialUI Tooltip into my React application with two separate text lines. The first line should serve as the main title, while the second line functions as a sublabel. In this screenshot provided, you can see where I ...

The issue arises when the cache code in jQuery Ajax interferes with the callback function, causing it to

I encountered an issue with my code related to cache. The problem arises when there is an ajax call with a callback in the success function. var localCache = { /** * timeout for cache in millis * @type {number} */ timeout: 30000, ...

Tips for adjusting the positioning of a div element in a responsive design

I am currently working on my website and facing a layout issue. In desktop mode, there is a sidebar, but in mobile view, the sidebar goes down under the content displayed on the left side. I would like the sidebar to appear at the top in mobile view, fol ...

Encountering an unidentified entity within a ReactJS application

Within a container, I've included a search bar inside a form element with two inputs - from and to, along with a submit button. Upon submitting the form, I create an OBJECT named query which looks like this: const query = { from : this.s ...

Which HTML element does each script correspond to?

Are there any methods to identify the script used in certain HTML elements? For instance, if I wish to determine the script responsible for creating a drop-down menu, I can locate the HTML and CSS for the menu but not the JavaScript (or other scripts). I ...

Display user account balances in real-time on the web browser by retrieving data from a secure private Ethereum

I am seeking to create a website that can display real-time updates of a user's wealth from a private Ethereum blockchain. Ongoing Issue (buggy) Currently, I have attempted to connect to a private Ethereum blockchain that is mining using a WebSocket ...

What is the best way to navigate through an XML document within the DOM of an HTML

I am facing an issue with HTML code. My goal is to navigate through an XML document directly from within the HTML code. Here is the XML code: <?xml version = "1.0"?> <planner> <year value = "2000"> <date month = "7" day = " ...

Tips for keeping a div element at the top of the page

I am looking to have a div stick to the top of the page when someone scrolls down When the page is scrolled, the green div with class stickdiv should automatically stick to the top var left = document.getElementsByClassName("stickdiv"); for( var i = 0; ...

Assigning a variable in jQuery to a PHP variable that has not been defined can halt the script

Here is the code snippet for a document ready function: $(document).ready(function(){ var id = <?php echo "" ?>; alert('boo'); if(id!=0){ $(' ...

There is no need for updates as git is already current for some mysterious reason

As a newcomer to git, I've been trying to wrap my head around it but still struggling. Can someone help clarify this for me? My question pertains to the 'master' branch in git which contains the following code: const list = [ 'h&ap ...

What could be causing the error I'm encountering while running the 'net' module in Node.js?

I am currently working with .net modular and have opened TCP port 6112. var net = require('net'); var server = net.createServer(function (socket) { //'connection' listener }); server.listen(6112, function () { //'listening ...

JavaScript tool package with non-JavaScript alternative

Currently in search of a reliable Javascript widget toolkit that boasts a modern UI design like Dojo, incorporates AJAX for navigation, and effects. Essential requirement is flexibility and seamless fallback to an HTML-only version for console users. Whi ...

Adjusting MongoDB settings to permit cross-origin requests

I'm still new to using MongoDB, so I'm in the process of familiarizing myself with it. My current goal is to send a JSON object to MongoDB from the client side using the JavaScript code below. var addUserButton = document.getElementById('a ...

Understanding the Event Context of Elements using Browser Development Tools

I'm currently investigating the functionality of the search feature on the React Documentation page: https://reactjs.org/ . It's known that they utilize DocSearch, but I'm interested in understanding the inner workings. At the moment, I&ap ...

Comparing the functionalities of C#, Python, and JavaScript, including rounding methods

There seems to be a difference in how decimal numbers are rounded in C# or Python compared to Javascript. I came across a solution for banker's rounding on Stack Overflow, but it doesn't work as expected in my scenario and leads to discrepancies ...

The model's function received the error message "Not a valid function."

My project involves NodeJS, Express, and Sequelize(mysql2)... I am encountering an issue where I keep receiving the error message "is not a function". I have created a model and defined a function in the model as shown below: module.exports = (sequelize, D ...