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

Semantic UI form validation is initiated by clicking any button

Within my Semantic UI form (<div class="ui form">), it seems that every button is triggering the form validation, even if it's not a submit button. I have two different types of buttons below: <button class="ui blue right labeled icon prima ...

Using React and TypeScript to pass member variables

My component Child has a member variable that can change dynamically. While I am aware of passing props and states, is there a more elegant solution than passing member variables through props or other parameters? class Child extends React.Component< ...

What is the best way to make a trail follow my shapes on canvas?

In my current project, I have implemented a feature where shapes are generated by spinning the mouse wheel. One specific shape in focus is the triangle, but other shapes follow the same generation process. The goal is to create a trail that slowly fades ...

"Learn the steps for accessing the most recent version of a ReactJS application from the server

I have my react app hosted on a Netlify domain. How can I ensure that users who have previously loaded older versions of the app are redirected to the most recent deployed version? ...

The class functions perfectly under regular circumstances but ceases to operate once it is initialized

I'm currently developing a bluetooth remote in React Native. The issue I am facing is that my BLE class works perfectly on its own, but certain sections of code seem to malfunction when implemented within another class. import BLE from './Core/BL ...

Encountering issues with accessing the clientWidth and clientHeight references of the DOM in Vue

Issue with 'clientWidth' and 'clientHeight' properties on Vue and Element types. <div class="invoice-step-detail" id="invoice" ref="invoice"> @Component({ name: 'CreateInvoice', co ...

Encountered an error 'Unexpected token ;' while attempting to include a PHP variable in a jQuery AJAX call

Trying to execute a PHP script that updates a deleted field in the database when you drag a specific text element to a droppable area. Currently, here is the droppable area code: <div class="dropbin" id="dropbin" > <span class="fa fa-trash-o ...

Combining strings within a string after a specific word with nested Concatenation

In a given string variable "str," I am looking to concatenate another string between "InsertAfterMe" and "InsertBeforeMe". str="This is a string InsertAfterMe InsertBeforeMe" s1="sometext" s2="soMoreText" aList=[1,2,3,4,5] The concatenated string shoul ...

Enumeration in zod validation

Currently, I am using a schema in zod and have an object. const escortTypeOptions = [ { value: "Nutrition", label: "תזונה" }, { value: "Training", label: "אימונים" }, { value: "Nutrition ...

Struggling to loop through a child in Firebase real-time database?

I'm struggling to retrieve a nested child from my database with the following structure https://i.stack.imgur.com/ZDs38.png I am attempting to get the URI from the Gallery object. When I log in, I can see this in the console https://i.stack.imgur.c ...

Customizing font size in React with Material UI: A comprehensive guide on adjusting the font size of the Select component

I'm currently working on a web application that utilizes React along with Material UI. My goal is to adjust the font size of the Select component. I've attempted to achieve this by utilizing the MenuProps property, as shown in the following code ...

Updating a route in Next.js? Make sure to remove the classList as you

Looking to remove a specific class whenever the route changes in Next.js, I've attempted the following approach: React.useEffect(() => { const activatedLink = router.query.tags const classActivated = document.querySelector('.'+activated ...

The compiler error TS2304 is indicating that it cannot locate the declaration for the term 'OnInit'

I successfully completed the Angular superhero tutorial and everything was functioning properly. However, when I close the CMD window running NPM and then reopen a new CMD window to reissue the NPM START command, I encounter two errors: src/app/DashBoard ...

Addressing memory leaks in React server-side rendering and Node.js with setInterval

Currently in my all-encompassing react application, there's a react element that has setInterval within componentWillMount and clearInterval inside componentWillUnmount. Luckily, componentWillUnmount is not invoked on the server. componentWillMount( ...

eliminating attributes from a JavaScript object

Seeking a method to strip object properties before sending them to the front-end. Why does this code work as intended: var obj = { name: 'cris', age: 22, } console.log(obj) //displays name and age delete obj.name console.log(obj) //dis ...

Choose checkboxes based on the checkboxes that were previously selected

My goal is to have a checkbox automatically selected based on the previously selected checkbox. For example, if I select the first checkbox (which has a specific class), then only the checkbox with the same class as the first one should be selected using j ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

When utilizing a computed property that accesses the Vuex state, the v-if directive alone may not function as expected without

Uncertain of the source of the issue, but the basic v-if functionality seems to be malfunctioning. <template> <div> <select v-model="col.code"> <option v-for="i in foo" :value="i.code" ...

Install the npm package if there have been modifications to the package.json file

In short: Can we make npm install run automatically before executing any npm script if the package.json file has been modified? Situation Summary Imagine you switch to a branch that has updated the package.json file. You try running npm run my-script, bu ...

What is the best way to give stacked bar charts a rounded top and bottom edge?

Looking for recommendations on integrating c3.js chart library into an Angular 6 project. Any advice or suggestions would be greatly appreciated! ...