2.0.0 • Published 5 years ago

@mrizki/qsi-store v2.0.0

Weekly downloads
-
License
-
Repository
-
Last release
5 years ago

react-native-store

Getting started

$ yarn add qsi-store or $ npm install qsi-store

Usage

  1. Create a new client by creating an instance of QStoreClient
    	import QStoreClient from 'qsi-store';
    	// constructor or something else
    	this.qStore = new QStoreClient(<COUCH_DB_URL>);
  2. register your CouchDB database as a collection by using registerCollection method
    		 	 this.qStore.registerCollection('todos');
    		 ```
  3. use getCollection to interact with your collection
    		 		this.qStore.getCollection('todos').localDb.<PouchDbMethod_API>
    		 ```

Example

import QStoreClient from 'qsi-store';

export default class Todos extends Component {

  constructor(props){
    super(props);
    this.qStore = new QStoreClient('http://192.168.99.100:5984');
    this.qStore.registerCollection('todos');
    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount(){
    this.qStore.getCollection('todos').localDb.changes({
        live: true,
        include_docs: true
    }).on('change', this.handleChange);
  }

  handleChange(change){
    const {doc} = change;
    if(!doc) return;
    if (doc._deleted) {
        this.removeTodo(doc);
    } else if(!change.deleted){
        this.addOrModifyDoc(doc);
    }
  }

  handleDetailChange(change){
    const {doc} = change;
    console.log("doc",doc);
  }

  removeTodo(doc){
      const todos = this.state.todos.filter((_doc)=> _doc._id != doc._id);
      this.setState({todos});
  }

  addOrModifyDoc(doc){
    const todos = this.state.todos.filter((_doc)=> _doc._id != doc._id).concat([doc]);
    console.log("state.todos",this.state.todos);
    console.log("todos",todos);
    
    this.setState({todos});
  }

  

  renderListItem = ({item})=>{
    return(
    <View style={styles.todo}>
        <Text>{item.name}</Text>
        <Text>{item.status}</Text>
    </View>);
  };

  renderHeader(){
    return (<View style={styles.header}><Text>Status : {this.state.status}</Text></View>)
  }

  render() {
    return (
      <View style={styles.todosContainer}>
        <FlatList
            style={styles.todos}
            data={this.state.todos}
            renderItem={this.renderListItem}
        />
      </View>
    )
  }
}