0% found this document useful (0 votes)
96 views10 pages

Manual de Crud Firebase

1. The document outlines steps to create a Firebase project and connect a React app to it. This includes installing Firebase and React Router packages, creating components, and setting routes. 2. Instructions are provided to modify App.js to fetch data from Firebase and display it, and to create components for adding, editing, and viewing documents. 3. The Create, Edit, and Show components are configured to add, update, and display individual documents by interacting with the Firebase database. This allows for basic CRUD functionality in the React app using Firebase as the backend.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views10 pages

Manual de Crud Firebase

1. The document outlines steps to create a Firebase project and connect a React app to it. This includes installing Firebase and React Router packages, creating components, and setting routes. 2. Instructions are provided to modify App.js to fetch data from Firebase and display it, and to create components for adding, editing, and viewing documents. 3. The Create, Edit, and Show components are configured to add, update, and display individual documents by interacting with the Firebase database. This allows for basic CRUD functionality in the React app using Firebase as the backend.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Paso 1.

Crear un proyecto en firebase

Paso 2.

Instalar firebase en nuestro proyecto

npm install --save firebase

Creamos un archivo Firebase j.s

import * as firebase from 'firebase';


import firestore from 'firebase/firestore'

const settings = {timestampsInSnapshots: true};

const config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);

firebase.firestore().settings(settings);

export default firebase;

Paso 4

Instalamos Router dom

npm install --save react-router-dom


npm install --save-dev bootstrap

creamos los componentes

 Create
 Show
 Edit

Paso 5

En nuestro index guardamos las rutas de los componentes que acabamos de crear
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import App from './App';
import Edit from './components/Edit';
import Create from './components/Create';
import Show from './components/Show';
import Appcss from './App.css'
import {
BrowserRouter,
Switch,
} from "react-router-dom";

import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
<Router>
<div>

<Route exact path='/' component={App} />


<Route path='/edit/:id' component={Edit} />
<Route path='/create' component={Create} />
<Route path='/show/:id' component={Show} />
</div>
</Router>,
document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
registerServiceWorker();

Paso 6

Modificamos nuestro archivo App.js

import React, { Component } from 'react';


import { Link } from 'react-router-dom';
import './App.css';
import firebase from './Firebase';

class App extends Component {


constructor(props) {
super(props);
this.ref = firebase.firestore().collection('coments');
this.unsubscribe = null;
this.state = {
coments: []
};
}

onCollectionUpdate = (querySnapshot) => {


const coments = [];
querySnapshot.forEach((doc) => {
const { title, description, author } = doc.data();
coments.push({
key: doc.id,
doc, // DocumentSnapshot
title,
description,
author,
});
});
this.setState({
coments
});
}

componentDidMount() {
this.unsubscribe = this.ref.onSnapshot(this.onCollectionUpdate);
}

render() {
return (
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
COMENT LIST
</h3>
</div>
<div class="panel-body">
<h4><Link to="/create">Add Coment</Link></h4>
<table class="table table-stripe">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Author</th>
</tr>
</thead>
<tbody>
{this.state.coments.map(Coment =>
<tr>
<td><Link to={`/show/$
{Coment.key}`}>{Coment.title}</Link></td>
<td>{Coment.description}</td>
<td>{Coment.author}</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
);
}
}

export default App;

Paso 7

Modificamos nuestro componente créate

import React, { Component } from 'react';


import ReactDOM from 'react-dom';
import firebase from '../Firebase';
import { Link } from 'react-router-dom';

class Create extends Component {

constructor() {
super();
this.ref = firebase.firestore().collection('coments');
this.state = {
title: '',
description: '',
author: ''
};
}
onChange = (e) => {
const state = this.state
state[e.target.name] = e.target.value;
this.setState(state);
}

onSubmit = (e) => {


e.preventDefault();
const { title, description, author } = this.state;

this.ref.add({
title,
description,
author
}).then((docRef) => {
this.setState({
title: '',
description: '',
author: ''
});
this.props.history.push("/")
})
.catch((error) => {
console.error("Error adding document: ", error);
});
}

render() {
const { title, description, author } = this.state;
return (
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
ADD COMENT
</h3>
</div>
<div class="panel-body">
<h4><Link to="/" class="btn btn-primary">Book
List</Link></h4>
<form onSubmit={this.onSubmit}>
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" name="title"
value={title} onChange={this.onChange} placeholder="Title" />
</div>
<div class="form-group">
<label for="description">Description:</label>
<textArea class="form-control" name="description"
onChange={this.onChange} placeholder="Description" cols="80"
rows="3">{description}</textArea>
</div>
<div class="form-group">
<label for="author">Author:</label>
<input type="text" class="form-control" name="author"
value={author} onChange={this.onChange} placeholder="Author" />
</div>
<button type="submit" class="btn btn-
success">Submit</button>
</form>
</div>
</div>
</div>
);
}
}

export default Create;

Paso 8

Modificamos nuestro componente edit

import React, { Component } from 'react';


import firebase from '../Firebase';
import { Link } from 'react-router-dom';

class Edit extends Component {

constructor(props) {
super(props);
this.state = {
key: '',
title: '',
description: '',
author: ''
};
}

componentDidMount() {
const ref =
firebase.firestore().collection('coments').doc(this.props.match.params.id
);
ref.get().then((doc) => {
if (doc.exists) {
const Coment = doc.data();
this.setState({
key: doc.id,
title: Coment.title,
description: Coment.description,
author: Coment.author
});
} else {
console.log("No such document!");
}
});
}

onChange = (e) => {


const state = this.state
state[e.target.name] = e.target.value;
this.setState({Coment:state});
}

onSubmit = (e) => {


e.preventDefault();

const { title, description, author } = this.state;

const updateRef =
firebase.firestore().collection('coments').doc(this.state.key);
updateRef.set({
title,
description,
author
}).then((docRef) => {
this.setState({
key: '',
title: '',
description: '',
author: ''
});
this.props.history.push("/show/"+this.props.match.params.id)
})
.catch((error) => {
console.error("Error adding document: ", error);
});
}

render() {
return (
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
EDIT COMENT
</h3>
</div>
<div class="panel-body">
<h4><Link to={`/show/${this.state.key}`} class="btn btn-
primary">Coment List</Link></h4>
<form onSubmit={this.onSubmit}>
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" name="title"
value={this.state.title} onChange={this.onChange} placeholder="Title" />
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control"
name="description" value={this.state.description}
onChange={this.onChange} placeholder="Description" />
</div>
<div class="form-group">
<label for="author">Author:</label>
<input type="text" class="form-control" name="author"
value={this.state.author} onChange={this.onChange} placeholder="Author"
/>
</div>
<button type="submit" class="btn btn-
success">Submit</button>
</form>
</div>
</div>
</div>
);
}
}

export default Edit;

Paso 9

Modificamos nuestro componente show

import React, { Component } from 'react';


import firebase from '../Firebase';
import { Link } from 'react-router-dom';

class Show extends Component {

constructor(props) {
super(props);
this.state = {
Coment: {},
key: ''
};
}

componentDidMount() {
const ref =
firebase.firestore().collection('coments').doc(this.props.match.params.id
);
ref.get().then((doc) => {
if (doc.exists) {
this.setState({
Coment: doc.data(),
key: doc.id,
isLoading: false
});
} else {
console.log("No such document!");
}
});
}

delete(id){
firebase.firestore().collection('coments').doc(id).delete().then(()
=> {
console.log("Document successfully deleted!");
this.props.history.push("/")
}).catch((error) => {
console.error("Error removing document: ", error);
});
}

render() {
return (
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h4><Link to="/">Coment List</Link></h4>
<h3 class="panel-title">
{this.state.Coment.title}
</h3>
</div>
<div class="panel-body">
<dl>
<dt>Description:</dt>
<dd>{this.state.Coment.description}</dd>
<dt>Author:</dt>
<dd>{this.state.Coment.author}</dd>
</dl>
<Link to={`/edit/${this.state.key}`} class="btn btn-
success">Edit</Link>&nbsp;
<button onClick={this.delete.bind(this, this.state.key)}
class="btn btn-danger">Delete</button>
</div>
</div>
</div>
);
}
}

export default Show;

You might also like