Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 323
chobo2 Avatar asked Feb 04 '23 10:02

chobo2


1 Answers

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();
like image 78
Tholle Avatar answered Feb 07 '23 03:02

Tholle