What is the best way to update the displayed data when using Mobx with an observable array?

Is there a way to re-render observable array data in Mobx? I have used the observer decorator in this class.


interface IQuiz {
    quizProg: TypeQuizProg;
    qidx: number;
    state: IStateCtx;
    actions: IActionsCtx;
}
@observer
class Comp extends React.Component<IQuiz> {
    private _qtype: common.TypeQuiz = '';
    private _qtime = 60;
    @observable _quizs: common.IQuizData[] = [];

    constructor(props: IQuiz) {
        super(props);
        makeObservable(this);
    };
    public componentWillMount() {
        this._quizs = this.props.actions.getData();
    }
    @action
    public quizSelect(idx: number, v: boolean) {
        this._quizs[idx].selected = true;
        this._quizs.slice();
    }
    public render() {
        const {state, actions, qidx} = this.props;
        let ItemComponent;
        if(this._qtype === 'unscramble') ItemComponent = QuizUnscramble;
        if(this.props.state.prog !== 'quiz') {
            return <QuizList
                state={state}
                quizs={this._quizs}
                quizSelect={(idx: number, v: boolean) => {
                    this.quizSelect(idx, v);
                }}
            />
        } else {
            return (
                <QuizBox
                    view={true}
                    className="t_quiz"
                    quizProg={state.quizProg}
                    qidx={qidx}
                    qtype={this._qtype}
                    qtime={this._qtime}
                    quizs={this._quizs}
                    ItemComponent={ItemComponent}
                    isteacher={false}
                    setQuizProg={actions.setQuizProg}
                />          
            );
        }
    }
}

const Quiz = useTeacher((store: TeacherContext) => (
    <Observer>{() => (
        <Comp 
            quizProg={store.state.quizProg}
            qidx={store.state.qidx}
            state={store.state} 
            actions={store.actions}
        />
    )}</Observer>
));

I am working with MobX6 and React TypeScript. However, the Comp class does not re-render when the quizSelect function is executed. It seems like @observable.deep is also not functioning properly. Could it be an issue with checking deeply nested mobx observable data points?

Does anyone know how to resolve this issue?

Answer №1

The problem seems to be originating from the componentWillMount function, specifically in how you are handling the array marked as observable. When dealing with arrays and objects, it is important to consider that they are reference types rather than value types.

To resolve this issue, try adding elements to the existing array instead of reassigning it:

public componentWillMount() {
    this._quizs.push(...this.props.actions.getData());
}

Answer №2

After some research, I discovered the solution. Reallocation of reference type is necessary.

this._quizs[idx].selected = v;
this._quizs = _.cloneDeep(this._quizs);

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

Issue with Bootstrap 3 Modal: Missing Title and Input Labels

I'm currently working on customizing a bootstrap template for my friend's church website. My goal is to create a simple web presence for them, and I am in the process of setting up a contact form. I want this form to appear as a modal where users ...

retrieving data from GET variables and sending to a PHP array

Is there a way to retrieve form variables and store them in an array in memory without reloading the page? I'm not very experienced with this, so any guidance would be appreciated. My goal is to update a JSON file using PHP based on form inputs. JSON ...

Issue with the successful execution of connection event handler in NodeJS and Socket.io?

When I look at my code in files named server.js and index.html, I notice that the io.on('connection') part is not executing the console.log method in its callback when I visit my server in the web browser. Take a look at the code snippets below ...

Kindly include an @Ionic3Annotation for either @Pipe, @Directive, or @Component

During development, this code runs without any issues. However, when attempting to run it in production using the command: Working: ionic cordova run android Not working: ionic cordova run android --prod --release Error Message: [03:34:41] types ...

Error message: The types in React Redux typescript are incompatible and cannot be assigned to each other

I recently converted my React App to TypeScript and encountered an error that I'm having trouble understanding. Any help would be greatly appreciated. Here is the code for my "mapStateToProps" function: function mapStateToProps(state: AppState): MapS ...

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...

The MongoDB query isn't functioning properly as the Match operation is returning an array with no elements

I am currently facing an issue with creating an aggregation pipeline. Everything seems to be working fine in the code until it reaches the $match section, which returns nothing. Here is the snippet of my code: var userId = req.params.UserId const m ...

"Utilizing the __proto__ property in Express.js for handling request

One issue that I've encountered is with the request.body generated by the express.urlencoded() middleware. Sometimes, it adds "__proto__" at the end of the request.body object, which makes it impossible to directly use it to initialize a mongoose mode ...

The interface is unable to populate the Array of Elements

When using Angular, I send a request and save the response in a variable: conversations: Conversation[]; // ChatService getConversations() { return this.http.get<Conversation[]>('/chat/conversations'); } this.chatService.getConversat ...

Looking for a modular approach? Incorporate specific parts of a module into the parent component

Developing a node.js module and aiming to organize my code effectively. My goal is to have individual files/folders for different parts of the module such as authentication, users, etc. These will be required from a parent package which will then expose t ...

Unable to fetch local file using ajax from a local HTML page

According to Same Origin Policy, the SOP should not be applied to the file:// protocol. However, I'm having trouble with my code. I am running a testing page from my local system, and both when I try to access abc.txt in the same directory as the HTML ...

Is there a way to send an array of objects using axios-http?

Currently, I am utilizing react-dropzone for uploading mp3 files and a metadata npm to extract all the file contents. However, upon sending it to axios.post(), an error is encountered stating "Body Exceeded 1mb limit" Here is the snippet where the new dat ...

Error encountered in Angular $injector:unpr while attempting to initialize uibModal

I followed the ui-bootstrap tutorial to create my code. On my homepage, there is a button that triggers a modal window to open using ng-click. However, when I check the dev tools, I encounter the following error: Error: [$injector:unpr] Unknown provider: ...

Steps to initiate or conclude a conversation from a designated location?

I'm working on an Angular project where I have a popup dialog open. However, I want the dialog to appear from the button and close within the button itself, similar to this example: https://material.angularjs.org/latest/demo/dialog Opening and closin ...

Leveraging promises in conjunction with mongoose operations

I'm new to using promises in conjunction with mongoose query functions such as find() and findById(). While everything seems to be functioning correctly, I am unsure if the way I am chaining then is the proper approach. The goal of utilizing promises ...

Creating client side scripts for an ajax call to generate a Json object is simple once you understand the basics

Typically, when I make ajax calls, I request pure HTML. However, for various reasons, I require guidance on constructing a table (let's say of individuals and their information) when receiving a Json object. While I am capable of creating a table in J ...

Difficulty with parsing JSON in JavaScript and retrieving values by key

I'm encountering an error response within the ajax error function; $.ajax(Request).error(function (Response) { var content = JSON.stringify(Response.responseText); var obj = JSON.parse(content); console.log("Response.r ...

Is it possible to achieve a height transition using CSS instead of relying on JavaScript

I created these custom cards using a combination of HTML, CSS, and JavaScript. However, I've noticed that the height transition animation is not as smooth as I'd like it to be, especially on certain pages. Is there a way to achieve this animation ...

Upon initializing mean.io assetmanager, a javascript error is encountered

I am eager to utilize the MEAN.io stack. I completed all the necessary initialization steps such as creating the folder, performing npm install, and obtaining the required libraries. Currently, in server/config/express.js file, I have the following code: ...

Preventing Undefined Values in RxJS Observables: A Guide

I am facing an issue with passing the result of a GET request from Observable to Observer. The problem lies in the fact that the value becomes undefined because it communicates with the observer before the GET execution finishes. observer:Observer<a ...