Post data to Firebase database with fetch()

December 2nd, 2022

  1. create a database in Firebase

  2. create form, connect input with data properties with v-model

1<template>
2 <BaseCard>
3 <h1 class="text-xl font-semibold mb-6">How was your learning experience?</h1>
4 <form @submit.prevent="submitSurvey" class="flex flex-col gap-8">
5 <div>
6 <label for="name">Your name:</label>
7 <input type="text" id="name" name="name" class="border ml-2" v-model.trim="enteredName">
8 </div>
9 <div class="flex flex-col gap-2">
10 <h3 class="text-lg">Please rate your learning experience...</h3>
11 <div class="flex gap-2 items-center">
12 <input type="radio" id="rating" name="rating" value="poor" v-model="chosenRating">
13 <label for="rating">Poor</label>
14 </div>
15 <div class="flex gap-2 items-center">
16 <input type="radio" id="rating" name="rating" value="average" v-model="chosenRating">
17 <label for="rating">Average</label>
18 </div>
19 <div class="flex gap-2 items-center">
20 <input type="radio" id="rating" name="rating" value="great" v-model="chosenRating">
21 <label for="rating">Great</label>
22 </div>
23 </div>
24 <BaseButton type="submit" class="self-start">Submit</BaseButton>
25 </form>
26 </BaseCard>
27 {{ enteredName }}
28 {{ chosenRating }}
29</template>
30 
31<script setup>
32import { ref } from "vue";
33 
34const enteredName = ref('');
35const chosenRating = ref('');
36 
37function submitSurvey(){
38 //
39}
40</script>
  1. submitSurvey(): post data to firebase database with fetch() method

    • when you create a database in firebase, you get url for that database, copy that and add yourChosenName.json at the end (because all data saved in firebase is in json format)

    • fetch(url, { options })

    • when posting data is successful, you have to reset the form (set properties back to null/empty string)

1function submitSurvey() {
2 console.log('submitSurvey was called'),
3 // fetch(url, { options })
4 fetch('https://survey-93121-default-rtdb.europe-west1.firebasedatabase.app/survey.json', {
5 method: 'POST',
6 headers: {
7 'Content-Type': 'application/json'
8 },
9 // send data in json format
10 body: JSON.stringify({
11 name: enteredName.value,
12 rating: chosenRating.value
13 })
14 })
15 
16 // reset the form to empty values
17 enteredName.value = '';
18 chosenRating.value = null;
  1. validate inputs

    • add new property invalidInput and set it to false at the start

    • if entered values are empty, set invalidInput to true, otherwise false

    • if invalidInput is true, display <p>Please fill in the fields</p> in the template

1const invalidInput = ref(false);
2 
3function submitSurvey() {
4 if(enteredName.value === '' || chosenRating.value === null) {
5 invalidInput.value = true;
6 return;
7 }
8 
9 invalidInput.value = false;
10 ...
1 <form @submit.prevent="submitSurvey" class="flex flex-col gap-8">
2 <p v-if="invalidInput" class="text-sm text-red-500">Please fill in all fields.</p>
3 ...
4</form>
  1. catch errors:

1const error = ref(null)
2 
3function submitSurvey(){
4 // validation
5 
6 // post data to url
7 fetch(url, {options})
8 .then(response => {
9 if(response.ok){
10 //
11 } else {
12 throw new Error('Try again later!');
13 }
14 })
15 // catch error (e) and set it to error property
16 .catch(e => {
17 e.message = error.value
18 })
19}
20 
21// if error property is set, show it in template
22<template>
23 <p v-if="error" class="text-red-500 text-sm">{{ error }}</p>
24</template>

our example:

1<script setup>
2import { ref } from "vue";
3 
4const enteredName = ref('');
5const chosenRating = ref('');
6const invalidInput = ref(false);
7const err = ref(null);
8 
9function submitSurvey() {
10 if(enteredName.value === '' || chosenRating.value === null) {
11 invalidInput.value = true;
12 return;
13 }
14 
15 invalidInput.value = false;
16 
17 fetch('https://survey-93121-default-rtdb.europe-west1.firebasedatabase.app/survey.json', {
18 method: 'POST',
19 headers: {
20 'Content-Type': 'application/json'
21 },
22 body: JSON.stringify({
23 name: enteredName.value, // .value because of ref('')
24 rating: chosenRating.value
25 })
26 }).then(response => {
27 if (!response.ok) {
28 throw new Error('Data could not be saved! Please try again later.')
29 }
30 }).catch(error => {
31 err.value = error.message;
32 })
33 
34 enteredName.value = '';
35 chosenRating.value = null;
36}
37</script>

Related Posts