Skip to content
This repository has been archived by the owner on Dec 31, 2020. It is now read-only.

Shared state for multiples instances of component #37

Closed
otbe opened this issue Apr 2, 2016 · 2 comments
Closed

Shared state for multiples instances of component #37

otbe opened this issue Apr 2, 2016 · 2 comments

Comments

@otbe
Copy link

otbe commented Apr 2, 2016

Hi,

I have a little component that wraps a button and shows up a "Loading" text if you click the button.
Something like that:

import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { observable } from 'mobx';

@observer
export class AsyncButton extends Component<void, {}> {
  @observable
  private isLoading: boolean = false;

  constructor() {
    super();
    console.log('constructor')
  }

  render () {
    console.log('render', this.isLoading);

    return (
      <Button
        onClick={() => this.isLoading = !this.isLoading}>
        {this.isLoading ? <span>Loading</span> : <span>Click me</span>}
      </Button>
    );
  }
}

ReactDOM.render(
  <div>
    <AsyncButton/>
    <AsyncButton/>
  </div>,
  document.getElementById('root'));

Expected result: two buttons, If I click button 1 text changes to "Loading" and console logs "render,true"
Actual result: two buttons, If I click button 1 text of button 1 and button 2 changes to "Loading" and console logs "render,true" twice. If I click button 1 again both buttons are re-rendered and text changes to "Click me".

Workarounds:

  • remove the export statement from the class definition
  • use extendObservable in the constructor instead of observable

Im using Typescript 1.8.9 (with experimentalDecorators set to true), mobx 2.0.4 and mobx-react 3.0.3

@otbe otbe changed the title One state for multiples instances Shared state for multiples instances of component Apr 2, 2016
@andykog
Copy link
Member

andykog commented Apr 2, 2016

@otbe I've tested your example and it works exactly as you expect. Check this repo: https://github.com/andykog/js-playground-mobx-react-shared-state-components (npm install && npm start)

@otbe
Copy link
Author

otbe commented Apr 2, 2016

You are right. This works as expected.
I have played around for while with your repo and I can reproduce the error if I add "react-hot-loader" for HMR support to the webpack chain. Switched to "react-hmre" babel preset for HMR.

So this is not a bug within mobx 👍

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants