Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

328
Visualizações
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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

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).

about 4 years ago · Juan Pablo Isaza Relatório

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda