mobxjs / mobx-react-lite

Lightweight React bindings for MobX based on React 16.8 and Hooks
https://mobx.js.org/react-integration.html
MIT License
2.13k stars 91 forks source link

how to reference other model in useLocalStore? #241

Closed hardfist closed 4 years ago

hardfist commented 4 years ago

It's very convenient do observable references to other observable, just like the following

export class Todo {
    id: number
    @observable text: string
    @observable done: boolean
    @observable deleted: boolean

    constructor(text: string) {
        this.id = generateTodoId();
        this.text = text;
    }
    toggleDone() {
        this.done = !this.done
    }
    remove() {
        this.deleted = true
    }
}

export class TodoList {
    @observable list: Todo[] = []

    get validTodos() {
        return this.list.filter(todo => !todo.deleted)
    }

    createTodo = (text: string) => {
        const todo = new Todo(text);
        this.list.push(todo)
        return todo;
    }
}

how to implement this in useLocalStore

danielkcz commented 4 years ago

Pretty much the same way. It might be useful you show what you have tried and did not work for you.

hardfist commented 4 years ago

@FredyC Thanks! I figure it out, There's nothing to do with useLocalStore, useState works fine for me, The reason I failed because I forget to wrap Todo Component with observer, which doesn't rerender event todo is changed . The demo is here https://github.com/hardfist/hooks-puzzle/blob/master/src/store/todo.store.ts

hardfist commented 4 years ago

I have another question, what's the difference between The following code when TodoStore is observable already https://github.com/hardfist/hooks-puzzle/blob/master/src/components/todo-mobx-local/index.tsx

const store = useLocalStore(() => new TodoStore());
const [store] = useState(() => new TodoStore()); 
mweststrate commented 4 years ago

Nothing 😊 and useState will do just fine

Op za 16 nov. 2019 14:27 schreef hardfist notifications@github.com:

I have another question, what's the difference between The following code when TodoStore is observable already https://github.com/hardfist/hooks-puzzle/blob/master/src/components/todo-mobx-local/index.tsx

const store = useLocalStore(() => new TodoStore()); const [store] = useState(() => new TodoStore());

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/mobxjs/mobx-react-lite/issues/241?email_source=notifications&email_token=AAN4NBBTGRB4GCQ2VKC436LQT77LRA5CNFSM4JOEONNKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEEHSWLA#issuecomment-554642220, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAN4NBA5Z356422DIQF5X73QT77LRANCNFSM4JOEONNA .