Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

113
Vistas
React & Mobx: render (via method render()) @observable data that will be modified after the specified component is rendered

Please advise how to solve the following problem:

There is a component that outputs some counter:

@observer class MyComponent extends React.Component {    
    render() {

        const data: MyData = new MyData();    

        return <div>{data['counter']}</div>;
    }
}

The counter is stored in a trackable (via mobx @observable) singleton:

export class MyData extends ISingleton
{
    @observable data: any = {}
}

At some point the counter (when MyComponent is already created) the counter is set

let data: MyData = new MyData(); 
data['counter'] = 123;

But MyComponent is not redrawn, although the component seems to track variable change (via mobx @observer and @observable)

Please advise where is the error and how can it be fixed

7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

In mobx you need manipulate the state of observers within actions.

You should extend your singleton to look something like this:

export class MyData extends ISingleton
{
    @observable data: any = {}

    @action 
    setCounter(val: number) {
        this.data = val
    }
}

Then call the setCounter-Method instead of manipulating the state directly.

Please take note that as of version 6 of MobX it is discouraged to use the decorator API (see this for more information).

7 months ago · Juan Pablo Isaza Denunciar

0

Every render creates a completely fresh new data object, effectively resetting it. So you want to store data at the class instance, not inside the render. Also the data you are modifying is completely different data than the data you are rendering (that is what the new keyword does). Probably you want to read up a little on how objects, classes & instances work in JavaScript in general

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.