chobo2
chobo2

Reputation: 85875

How to use @Action in Mobx + reactjs?

I am confused on how to use @action in my code.

class Items {

  @observable items= [];

  @action addItem() {
    let newItem= new Item();
    items.push(newItem);
  }
}

@observer
class ItemPage extends Component {

  constructor() {
    super();
  }

  render() {
    const {addItem} = this.props.store;
    return (
      <div className="items">
        <input type="button" value="add" onClick={addItem}/>
      </div>
    )
  }
}

const store = new Items();

Upvotes: 4

Views: 3245

Answers (1)

Tholle
Tholle

Reputation: 112917

Make sure that you alter this.items and not just items. You also need to bind either the action with action.bound or create a bound handler in the component:

class Items {
  @observable items= [];

  @action.bound
  addItem() {
    let newItem = new Item();
    this.items.push(newItem);
  }
}

@observer
class ItemPage extends Component {
  render() {
    const { addItem } = this.props.store;
    return (
      <div className="items">
        <input type="button" value="add" onClick={addItem}/>
      </div>
    );
  }
}

const store = new Items();

Or:

class Items {
  @observable items= [];

  @action
  addItem() {
    let newItem = new Item();
    this.items.push(newItem);
  }
}

@observer
class ItemPage extends Component {
  handleClick = () => {
    this.props.store.addItem();
  };
  render() {
    return (
      <div className="items">
        <input type="button" value="add" onClick={this.handleClick}/>
      </div>
    );
  }
}

const store = new Items();

Upvotes: 8

Related Questions