---
# System prepended metadata

title: Summer B Week 5 Tinker

---

# Summer B Week 5 Tinker 

## Firestore Writing Data
### Creating Data
Questions:
* Which part are we writing data to the database?
    * Fill out the input, click on Add Album button and watch the data change in the database. 
    > After filling out the input and clicking the Add Album button, a new component was added in the page, and a new document including artist and album name, was added into the collection of "album".
    > 
    > We were writing data to the database using the `methods` of `creatAlbum`. Then, through `this.reset()`, we reset the form. Lastly, through  `this.readAlbums()`, a new component was added to the page.


* Hook up createAlbumAlternate() instead of createAlbum()
    * What does createAlbumAlternate() do?
    > This is another method that is used to add a new component in the page, which is also used to add a new document into the collection "albums".
    * How is it different than createAlbum()?
    * What do you think `let id = albumsRef.doc().id` is doing?
    >When we were using`createAlbum()`,the new document only included "artist" and "name". When we changed`createAlbum()`into `createAlbumAlternate()`, the automatically generated id was also in the field. Inside the method`createAlbumAlternate()`, there is `let id = albumsRef.doc().id`, which created a new document called "id". Then, inside `albumsRef.doc(id).set`, there is `id: id`, which means that the new added document will have another field "id", which refers to the "id" in the document "id". Therefore, a new document including artist, album name, and the automatically generated id, was added into the collection of "album".
    >Add the `let id = albumsRef.doc().id` will be more convenient when we want to access the information of id.
    

### Writing Data - Create

* In your own project, create a new collection todos.
    * Database: https://console.firebase.google.com/u/0/project/city-of-data-55996/firestore/data/~2Ftodos~2Fr1ALIYgALmUt0s72vt35
    
* Create a reference variable to the todos collection in your Vue project.
    * Codepen URL: https://codepen.io/yl4516/pen/zYwWePy?editors=0010

* When a user inputs a task and then click the ADD button, that new task should be added to the todos collection.
    * When should the Vue app "write" data to the DB?
    
    >We did not understand what does this question want to ask actually. So from our point of view, we think that after linking the database and the application (e.g. `let db = firebase.firestore();
let todosRef = db.collection('todos');` and the configuration code), we started to "write" data to the DB.
    
    * Where we are writing the new task to?
    >We are writing the new tasks (new documents) to the collection "todos".
    * What fields will thseat new task have?
    > 1. The name of the task: `task`
    > 2. A boolean that represents the state of the task (have done or not have done): `done`(true or false).
    > 3. The automatically generated id of the todo


### Updating Data
* Which parts are we updating data in the database?
>We were updating the number of the field "positive" in the database.
* Input a number and click update
    * What do you observe? 
    > The typed number was updated to the number in the component.
    * What changes? What doesn't change?
    >In the database, the number of field "positive" was updated as we typed new numbers in the input box. The other fields (id, death, name, recovered) did not change.
    * Why some data changes and the other not?
    >Because in the codepen application, we created the method that could only change the number of "positive":
    ```
    updateState(id) {
      statesRef.doc(id).update({
        positive: this.updatePositive,
      
      });
      this.updatePositive = null
      this.readStates();
    },
    ```
    * Instead of `docRef.update({num:1})` what might happen if we did `docRef.set({num:1})` ?
    >If we did `docRef.set({num:1})` using the `set` method, all the data in the database, including the id, death, name, recovered, would be replaced by the updated data of positive number, and all the other fields except for "positive" would disappear since the whole document was replaced by the new updated positive number.
---
### Writing Data - Update

Hands-On Activity:
Starter code: https://codepen.io/jmk2142/pen/LYydGGd
  Steps: 
-    Create a reference to the todos collection.
```javascript=
let todosRef =  db.collection('todos');
```
-    Create a component method in the root Vue instance that:
        -    Has parameters that can takes the todo ID argument from the child component (See $emit)
        -    Uses that ID to create a document reference.
-    Updates the todo task in the database.
```javascript=
updateTodo(id, task) {
      todosRef.doc(id).update({
        id: id,
        task: task
      });
    }
```
- What is missing from this UX?
Unable to mark whether a task is done or not, referring to the ```done``` field in the firestore.

---
### Deleting data

-    Let's click on the delete button and observe what happens in the database.
        -  It gets deleted in the database
-    Which part are we deleting the data in database?
        -  The whole document gets deleted including all fields.
-    How does it work?
        -  The method called ```delete()```
-    Why do we need to use $emit?
        -  Using emit enables the method to listen for the click targeting the specific object and then to execute the method on it.
-    What are we passing in as the second argument?
        -    We pass in the ```tweet.id``` as the second argument.
-    What happens if we remove this.readTweets(); ?
        -    When we delete the ```this.readTweets()```in the ```deleteTweet()```, the whole app stopped popping tweets and when the whole tweets got deleted manually, it cannot restore when clicking the restore button.
---
### Create a reference to your todos collection.
-    When user clicks on delete button, make it so that the target document is deleted:

https://codepen.io/xl3095/pen/LYymGgB

-    Think about how the computer knows which document the user is targeting.
I am guessing the computer grab data based on the user input, such as URL from the reference object and then using the emit to target the specific one that the user is interacting with, for instance, we use id as a flag, finally implement the action based on the function tied to it.



## Firestore Reading Data 

### Reading Document Data 
Questions:
* What's the reference of the data read from the database? 
> 
```
let db = firebase.firestore();
let stepsRef = db.collection('steps');
```
The data referenced from the firestore database is the collection called "steps". 
* Explain the relationship between the data in database and data displayed in the app.
>
```
stepsRef.doc('wash').get().then(doc => {
        console.log(doc.data())
        console.log(doc)
        this.step = doc.data()
      }).catch(error => {
        console.log(error)
      })
```
When the function readStep is mounted, Vue will look to the firestore database and find the document "wash" in the collection "steps". It will then get this data and display it, which would then allow us to view the picture of hands being washed. 
* What is the difference between doc and doc.data() ?
    * Uncomment Line 12 and 13 in codepen example and go to debug mode.
>Doc refers to the document whereas doc.data() is the data within the document. So essentially Vue first has to confirm whether this "doc" actually exists, and if it does, then it will extract data from the document. 

Extra:
* How would you change the code / data architecture if you wanted to read a collection of steps?
>You would need to call on the collection called "stepsALT" instead. 
>This is our initial attempt: https://codepen.io/rd2705/pen/zYwRzPo
>This is after seeing the solution code: https://codepen.io/rd2705/pen/wvdyqEz 

Hands-on Activity 
>Codepen: https://codepen.io/rd2705/pen/LYyQjRJ

---

### Reading Collection Data 

Questions:
* What are the differences between reading document data and reading collection data?
>Reading document data is usually only looking at data fields within the document itself. Reading collection data on the other hand allows you to pull data from all documents and fields within the collection. 
* From the lines where we are reading data, what are the major difference?
>We need to V-bind in the html. We have created an array for steps. Most importantly, we are using querySnapshot instead of get. 
```
<div class="step" v-for="step in steps">`

let stepsArr = [];
stepsRef.get().then(querySnapshot => {
        querySnapshot.forEach(doc => {
          console.log(doc.data())
          stepsArr.push(doc.data())
        })
        this.steps = stepsArr
      }).catch(error => {
        console.log(error)
      })
```
* What does forEach() method indicate to you? Take a guess on what does forEach() method do?
>As we can see in the code above, querySnapshot allows us to use a .forEach() method. This method will help us look through each doc to find the data we need. Since we defined an array for steps, we no long need to extract individual fields using .data(), instead we can create a loop that will save us the trouble! 
* What are the relationships between code parts and how data "moves" from: 1) the database, 2) the component, 3) the view/display?
>1) The data is first created in our firestore database. After we have created collections, documents, and fields, we can link this to the codepen by referencing the script of the data: 
```
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.10.0/firebase-app.js"></script>

<!-- Add SDKs for Firebase Firestore-->
<script src="https://www.gstatic.com/firebasejs/7.10.0/firebase-firestore.js"></script>

<script>
  // Your web app's Firebase configuration
  const firebaseConfig = {
    apiKey: "AIzaSyDJHhNR8H7cUxRoW2udifdtRddUqWn2Rw4",
    authDomain: "mstu5013-classwork.firebaseapp.com",
    databaseURL: "https://mstu5013-classwork.firebaseio.com",
    projectId: "mstu5013-classwork",
    storageBucket: "mstu5013-classwork.appspot.com",
    messagingSenderId: "101731794475",
    appId: "1:101731794475:web:b2df979e7d2b255ef5346e",
    measurementId: "G-EYWKRQ4W56"
  };
  
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
</script>
```
>Then, in Vue.js, we need to call on the database and create a name for our reference: 
```
let db = firebase.firestore();
let stepsRef = db.collection('stepsALT');
```
>2) We would need to create a component that uses the data from the database:
```
let app = new Vue({
  el: "#app",
  data: {
    steps: []
  },
  methods: {
    readSteps() {
      let stepsArr = [];
      stepsRef.get().then(querySnapshot => {
        // console.log(querySnapshot)
        querySnapshot.forEach(doc => {
          console.log(doc.data())
          stepsArr.push(doc.data())
        })
        this.steps = stepsArr
      }).catch(error => {
        console.log(error)
      })
    }
  },
  mounted() {
    this.readSteps()
  }
});
```
>This is usually done first by inputting the reference array in data. And then in methods, we would need to call on the firestore data. Depending on using collections or documents, we would determine whether to use 'get' or querySnapshot. Once the data is mounted, we are ready to display it. 

>3. To display the data, we need to add some references to our html code: 
```
<div id="app">
  <h2>Take Steps to Protect Yourself and Others</h2>
  <div class="step" v-for="step in steps">
    <img :src="step.photoURL">
    <p>{{ step.name }}</p>
  </div>
</div>
```
In addition to our typical Vue code beginning, we need to reference the data in firestore using our reference name under data in Vue.js inside the curly braces. If we are referencing a collection and there is an array, then we would need to create v-binds (for images in this case) and a v-for to call on several documents at the same time. 

Hands-on Activity 
* Codepen: https://codepen.io/rd2705/pen/jOmZGMz
