hieunguyen
2/19/2019 - 4:42 AM

example react component using firestore API

example react component using firestore API

import React, {Component} from 'react';
import {} from 'semantic-ui-react';
import database from "../Blog/config/firestore";
import {Button, Container, Form, Message, List} from "semantic-ui-react";

class TestFirestoreAPI extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: false,
            message: '',
            post: {
                id:'',
                title: '',
                content: ''
            },
            posts: []
        }
    }

    async componentDidMount() {
        await this.fetchPosts();
    }

    fetchPosts = async () => {
        this.setState({isLoading: true})
        await database.collection('posts').limit(10).get().then(
            (col) => {
                this.setState({isLoading: false})
                this.setState({posts: col.docs});
            }
        )
    }

    handleChange = (e, { name, value }) => this.setState({post: {...this.state.post, [name]: value }});

    onSearchClick = async () =>  {
        console.log(this.state.post);

        const post = await database.ref('posts/' + this.state.post.id);
        console.log(post);
    }

    pushData = async () => {
        this.setState({isLoading: true})
        if (this.state.post.id) {
            const post = database.collection("posts").doc(this.state.post.id);

            post.set(this.state.post).then(() => {
                this.setState({message: "Document written"})
            }).then(() => {
                return this.fetchPosts();
            }).then(() => {
                this.setState({isLoading: false})
            });
        } else {
            database.collection("posts").add(this.state.post).then((docRef) => {
                this.setState({message: "Document written with ID: " + docRef.id})
            }).then(() => {
                this.fetchPosts();
            }).then(() => {
                this.setState({isLoading: false})
            })
        }
    }

    pullData = async () => {
        const post = await database.ref('posts/' + this.state.post.id);
        post.on('value', (snapshot) => {
            console.log(snapshot.val());
            this.setState({post: {...this.state.post, content:  snapshot.val().content}})

        })
    }

    onNewPostClick = () => {
        this.setState({post: {id: '', title: '', content: ''}});
    }

    loadItem = (item) => {
        this.setState({post: {...item.data(), id: item.id}});
    }

    wideAllPosts = () => {
        this.state.posts.forEach(item => item.ref.delete());
    }

    render() {
        return <Container>
            <Form success={!!this.state.message} loading={this.state.isLoading}>
                <Form.Input name="title" value={this.state.post.title} placeholder='title'
                            onChange={this.handleChange}/>
                <Form.Input name="content" value={this.state.post.content} placeholder='Content'
                            onChange={this.handleChange}/>

                <Message success header='Add Post Completed' content={this.state.message}/>

                <Button onClick={this.onNewPostClick}>New</Button>
                <Button onClick={this.pushData}>Save</Button>
                <Button negative onClick={this.wideAllPosts}>Wipe Posts</Button>
            </Form>

            <List>
                {this.state.posts.map((item) => <List.Item as="a" key={item.id} onClick={() => this.loadItem(item)}>{item.get('title')}</List.Item>)}
            </List>
        </Container>
    }
}

export default TestFirestoreAPI;
import firebase from 'firebase';

const config = {
    apiKey: "AIzaSyCSjxrL6EDBp_lOXM0OisoLbI2-Y0FgbAw",
    authDomain: "blog-cb596.firebaseapp.com",
    databaseURL: "https://blog-cb596.firebaseio.com",
    projectId: "blog-cb596",
    storageBucket: "blog-cb596.appspot.com",
    messagingSenderId: "456316091688"
};

firebase.initializeApp(config);

const database = firebase.firestore();

// Get a reference to the database service
export default database;