Incorporating items into a dynamic array using MobX

Issue with Pushing MobX Objects to an Observable Array

I'm facing a challenge when trying to push objects into an observable array in MobX and iterate over them successfully.

At the starting point, I initialize the observable array:

if (!self.selectedGlobalFilters) self.selectedGlobalFilters = observable([])

Then I try to push the object filter.options01:

Proxy {Symbol(mobx administration): ObservableObjectAdministration$$1}
  [[Handler]]: Object
    [[Target]]: Object
      key: "status"
      value: "rejected"

However, upon pushing it using:

self.selectedGlobalFilters.push(filter.options01)

The result is:

[Proxy]
  0: Proxy
    [[Handler]]: Object
      [[Target]]: Object
        key: "status"
        value: "rejected"

Subsequently, attempting to push another object, filter.options02, shows a similar behavior:

Proxy {Symbol(mobx administration): ObservableObjectAdministration$$1}
  [[Handler]]: Object
    [[Target]]: Object
      key: "status"
      value: "done"


self.selectedGlobalFilters.push(filter.options02)

Resulting in:

[Proxy]
  0: Proxy
    [[Handler]]: Object
      [[Target]]: Object
        key: "status"
        value: "done"

The main issues are that the second push overrides the first and the desired data structure should be like this:

[{…}]
  0: 
    status: "rejected"
  1:
    status: "done"

TLDR; How can I achieve the desired outcome of pushing objects into an observable array that can be iterated on effectively?

Slicing the array has not produced any different outcome. Any guidance or assistance on this matter would be greatly appreciated. Thank you!

Answer №1

One of the main issues here seems to be that you are only observing a single variable instead of mapping the entire array!

@observable selectedGlobalFilters = [];

if (!this.selectedGlobalFilters.length) 
  this.selectedGlobalFilters.push(filter.options01)

Alternatively,

const gFilter = toJS(this.selectedGlobalFilters)
  this.selectedGlobalFilters = gFilter.push(filter.options01)

..in case the issue persists:-)

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

Swapping the image source using a Vue dropdown menu

Recently I started using Vue and decided to implement a dropdown menu component (). The component pulls its list items from a JSON array structured as follows: <template> <div id="app"> <div id='container'> ...

Why does my array become empty once it exits the useEffect scope?

const [allJobs, setAllJobs] = useState([]); useEffect(() => { axios.get('http://localhost:3002/api/jobs') .then(res => setAllJobs(res.data)); allJobs.map((job, i) => { if (job.language.toLowerCas ...

Guide on how to retrieve additional data from the API by pressing the "Load More" button

Hello, I am working on a project where I aim to display user data from an API called https://reqres.in/api/users?page=(the page number can be 1,2 or more) and present it in an HTML table using JavaScript with promises. Currently, I have successfully popula ...

Adjust the styling of the anchor tag within the selected div by utilizing jQuery

I am struggling with changing the color of a specific anchor tag when clicked inside a div with class .product_wishlist. Currently, all anchor tags within .pw div are changing colors. Is there a way to apply selected css only to the clicked element? Any he ...

What is the best way to delay an observable from triggering the next event?

In my Angular project, I am implementing RxJs with two subjects. s1.next() s1.subscribe(() => { // perform some operation and then trigger the event for s2 s2.next() }); s2.subscribe(() => { // perform some operat ...

ways to change date format in a React.js application using JavaScript

<b>Choose Date and Time</b><br/> <DateTimeField onChange={this.clockevent} format={"x"}/> clockevent=(newDate)=>{ var dateVal ="/Date("+newDate+")/"; var date = new Date(parseFloat(dateVal.substr(6))); console.log( ...

Clicking the mouse within three.js

I'm facing an issue with my webpage that features a three.js (webgl) graphic created using a .dae file imported from Blender. My goal is to draw a square or mark wherever the mouse is clicked, but for some reason, the square appears in a different loc ...

Guide to setting up CKeditor

I am struggling with the installation of CKEditor. After downloading the editor from the website, I inserted the code below between the head tags of my webpage: <script type="text/javascript" src="ckeditor/ckeditor.js"></script> <script typ ...

When attempting to check and uncheck checkboxes with a specific class, the process fails after the first uncheck

I have a set of checkboxes and one is designated as "all." When this box is clicked, I want to automatically select all the other checkboxes in the same group. If the "all" box is clicked again, I would like to deselect all the other checkboxes. Currently ...

Tips for creating equal height columns in Bootstrap 4

Working with Bootstrap 4 Beta in an attempt to create two columns that maintain full height regardless of screen size. The code below functions perfectly, ensuring both columns maintain full height across all devices. However, upon inserting the bootstra ...

Unusual structure declaration

While I am quite comfortable working with structs and arrays in C, the code snippet below has left me confused. Typically, a struct declaration looks something like this: struct employee { char title; int year; } mark; However, in the code provided, ...

What is the procedure for utilizing the comparator to arrange items according to various attributes?

I am trying to find a way to arrange my models in a collection based on their required flag and then alphabetically by their value. This is what my current code looks like: var myModel = Backbone.Model.extend({ defaults: { required: true, ...

Making an Http Get request in Angular 2 by passing a JSON object

How can I make an HTTP GET request and send a JSON object along with it? Here is the JSON object: {{firstname:"Peter", lastname:"Test"} I want to pass this object in the HTTP request to receive a list of matched persons. Is this possible? The example o ...

Implementing Twitter Login with Vue, Vuex, and Firebase

Exploring a Twitter login option for my sports social media dashboard project, I followed a helpful tutorial. While I've successfully implemented the HelloWorld component and retained the app.vue and main.js components, I encountered an error stating ...

Tips for stopping the textarea from moving around as you type and avoid it hitting the bottom of the page: Utilize JQuery and

As I type into the auto-sizing textarea, the text runs to the bottom of the page and causes it to dance uncontrollably with each key press. This forces me to constantly scroll down to see what's happening. How can I prevent this page dancing and keep ...

looking to display the latest status value in a separate component

I am interested in monitoring when a mutation is called and updates a status. I have created a component that displays the count of database table rows when an API call is made. Below is the store I have implemented: const state = { opportunity: "" } ...

Pass information from Vue JS v-for to a button when it is clicked

Just started learning Vue JS and encountered a small issue I'm currently looping through an array with a button inside the div I'm iterating over The goal is to grab the data of the selected item after clicking on the button For example, suppo ...

Challenges with retrieving all text records in a profile using ethers.js

Currently, I am facing difficulties in retrieving all ENS text records from a profile due to issues with the logic or potential approaches... With ethers.js v6, my current strategy involves fetching all the log data and then sifting through it. However, t ...

A guide to seamlessly adding calendar events with JSON data using the powerful Ionic Native Calendar Plugin

Hello there, I am in the process of developing an Ionic app and incorporating the Ionic Native Calendar plugin. My goal is to utilize this plugin to dynamically adjust the calendar event parameters through JSON linked to a Firebase database, rather than h ...

Angular: The function t(...) does not support success - TypeError

My code is generating the error TypeError: t(...).success is not a function. I have tried searching for a solution but haven't been able to figure out why this error is happening in my specific case. Here is a snippet of my JS code. Can anyone point ...