Newton Sheikh
Newton Sheikh

Reputation: 1396

Mobx Observable Array

I am stuck with this nasty error. I have an Observable array which i am filling using Axios Get request.

getVirtualMachines(){
    request.get('/Home').then(response => {
       console.log(response.data[0].name);
        this.virtualMachines = response.data;
    }).catch(error => {
        console.log(error);
    })
} 

Observable Array looks like

@observable virtualMachines: [{
    id: string,
    ip: string,
    name: string,
    power: string,
    sku: string
}]; 

I am calling this uisng componentWillMount(){ this.props.store.getVirtualMachines(); }

Now in the render method i am this

let vms: VirtualMachine[] = this.props.store.virtualMachines;
console.log(vms);

So far so good. Now i am trying to map the Vms array using slice() to convert the observable array to vanilla array and i get errors after errors

render(){
let vms: VirtualMachine[] = this.props.store.virtualMachines;
console.log(vms.slice());
....
....
}

Uncaught TypeError: Cannot read property 'slice' of undefined

warning.js:33 Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

i used the slice method by doing only

console.log(vms.slice());

Upvotes: 1

Views: 2889

Answers (1)

Tholle
Tholle

Reputation: 112777

You don't have a virtualMachines array on your first render. You could do something like this, to give your array a default value of an empty array:

class Store {
  @observable virtualMachines: [{
    id: string,
    ip: string,
    name: string,
    power: string,
    sku: string
  }] = [];

  getVirtualMachines(){
    request.get('/Home').then(response => {
      this.virtualMachines.replace(response.data);
    }).catch(error => {
      console.log(error);
    });
  } 
}

Upvotes: 2

Related Questions