GETTING STARTED

npm install --save mobase

Let's say we expect to have our data structured as follows (yes, this is a todo list):

1) First of all let's create a Mobase store

// don't forget to firebase.initializeApp(credentials)

const todoStore = new MobaseStore({
     path: '/todos',
     database: firebase.database(),
     fields: {
         id: observable.ref,
         isDone: {
             modifier: observable.ref,
             default: ''
         },
         subtasks: {
             modifier: observable.shallow,
             default: []
         },
         text: observable.ref
     }
})

2) Now let's use the store created in a reactive manner with React.

import {observer} from 'mobx-react'

const App = observer( ({todoStore}) => {

    return (
        <main>
            <div>Total: {todoStore.size}</div>

            <ul>
                {todoStore.values().map( item => (
                    <li key={item.id}>
                        {item.text}

                        {item.subtasks.map( (subtask, i) => (
                            <div key={i}>{subtask}</div>
                        )}
                    </li>
                ))}
            </ul>
        </main>
    )

} )

ReactDOM.render(<App todoStore={todoStore} />, document.getElementById('app'))

3) Add an item

const addTodo = text => {
    todoStore
         .write({ text })
         .then( id => console.log('New item id: %s', id) )
}

addTodo('This is a new task')

4) Modify an item

const completeTodo = todo => {
    todoStore
        .update( {id: todo.id, isDone: true} ) // don't forget to specify id of the object being updated
        .then( id => console.log('Updated successfully, id: %s', id) )
}


const addSubtask = (todo, subtask) => {
    const subtasks = todo.subtasks.slice().concat( subtask ) //new subtasks array

    todoStore
        .update( {id: todo.id, subtasks } )
        .then( id => console.log('Updated successfully, id: %s', id) )
}


const todo = todoStore.values()[0] //getting the first todo from the store
completeTodo(todo)
addSubtask(todo, "Yet another subtask")

5) Delete an item

const removeTodo = todo => {
    todoStore
         .delete(todo.id)
         .then( id => console.log('Deleted item %s', id) )
}

//fetch the first item
const firstTodo = todoStore.values()[0]

//and remove it
removeTodo(firstTodo)

results matching ""

    No results matching ""