0

I'm trying to access a method's objet (here greet() method) throught a mobx array, but I'm stuck with :

TypeError: person.greet is not a function

Person class

I have a Person class, with greet method :

export class Person {
    public id: number = Date.now();
    public firstName!: string;
    public lastName!: string;

    public greet() : string {
        return "Hello!";
    }
};

Store

My store look like :

import { persist } from "mobx-persist";
import { observable, computed, action } from "mobx";
import { Person } from "../models/Person";

export class PersonStore {

    @persist('list')
    @observable
    personList: Person[] = [];

    @computed get entries(): Person[] {
        return this.personList.slice();
    };
};

In the component

In my component, I pass the list like that :

const PeoplePage_: React.FunctionComponent<{ personStore: PersonStore }> = ({ personStore }) => {

    return (
        <PeoplePage
            personList={personStore.entries} />
    );
};
export default inject("personStore")(observer(PeoplePage_));

And then in my PeoplePagecomponent, when I'm doing something like :

personList[0].greet()

I'm getting the error.

Xero
  • 3,951
  • 4
  • 41
  • 73

1 Answers1

0

The issue was with the lib mobx-persist and then the line @persist('list')

This mean that my array is stored and the retrieved in plain object style ({firstname: 'foo', lastname: 'foo'}).

The trick is to construct a new Person in the component.

I added a constructor with an objet to repopulate.

export class Person {
    public id: number = Date.now();
    public firstName!: string;
    public lastName!: string;

    constructor(private obj: any = null) {
        if(obj){Object.assign(this, obj)}
    }

    public greet(): string {
        return `Hello, ${this.firstName}`;
    }
};

Then in my component:

new Person(person).greet()

Xero
  • 3,951
  • 4
  • 41
  • 73