How to Build a Simple Ionic E-Commerce App with Firebase
source link: https://devdactic.com/ionic-e-commerce-firebase/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to Build a Simple Ionic E-Commerce App with Firebase
February 23, 2021 By Simon 0 Comments
If you want to build an Ionic E-Commerce app, Firebase is a great backend alternative to existing shop systems. This is a quick yet still robust solution for a full blown shopping app!
In this tutorial we will setup a Firebase project with dummy shopping data inside Firestore. To keep it simple, we are not adding authentication although this would be quite easy afterwards following other material on Firebase authentication.
Once we got some dummy data we will build an Ionic app that loads data from Firebase and also uses Firestore to keep track of the cart and stock amount of products until we perform a dummy check out and clear all items.
We won’t integrate payments in this basic tutorial, but we have different courses inside the Ionic Academy in which we use Braintree for Paypal and also Stripe with Firebase!
Firebase Project Setup
Before we dive into the Ionic E-Commerce app, the first step is Firebase, and you need to create a new project (or use any existing). Inside Firebase, make sure you have enabled the Firestore database by clicking “Get Started” in the right tab.
Once you have created the project you need to find the web configuration which looks like this:
If it’s a new project, click on the web icon to start a new web app and give it a name, you will see the configuration in the next step now.
Leave this config block open until our app is ready so we can copy it over!
Upload Dummy Data to Firestore with Node
Most likely you have some existing product data or don’t want to create all listings by hand. For this, I found a great video containing an upload script, and I have modified some element to make it work with the latest version of Firebase.
If you want to build your own Firestore upload tool, simply create a folder and init a new Node project, plus install two dependencies:
Inside that folder you can now create a uploader.js file which basically creates the connection to your Firebase project using a service key.
To generate this key, navigate inside your Firebase project to Users and permissions and select the Service accounts tab. From here, scroll down and hit Generate new private key which you can copy to your just created project and rename it to service_key.json.
Now back to the uploader.js, which only scans a files folder for documents and uploads them directly to Firebase. Go ahead and fill that file with the following code:
The collection name will be used from the file, and the rest of the information is taken from the JSON data. I slightly changed the script to simply add()
all items to the collection which generates a random ID for each document – in the initial version you could also specify a fixed ID instead.
To make life easier, I took an export of the the products data from the cool Fakestore API and changed a few parts of it for our example.
If you want to follow along, create a file at files/products.json now and insert the following data:
Now all you got to do is run the uploader script from the command line and your Firestore data will contain all the great testing data:
If you followed along, your Firestore data should now look like this:
If you want to manually manage the products you could also create another app to manage the product listings, something we did inside the Marketplace course inside the Ionic Academy!
Setting up the Ionic E-Commerce App
Now we are ready to dive into the Ionic E-Commerce app and start with a blank new app and add the AngularFire schematic which will install all the necessary packages.
Additionally we generate a page and service for the rest of our functionality, so get started now with:
Now we need the configuration from Firebase that you hopefully kept open in your browser, and we can add it right inside our environments/environment.ts like this:
With the configuration in place we can initialise the connection from our Ionic app to Firebase by adding the according modules to our app/app.module.ts and passing in the environment from before:
That’s all for the setup and we can now connect to Firebase from our Ionic app!
Creating the Product and Cart Logic
First of all we will implement the backbone of our app, the service that manages the products and cart and connection to Firebase.
Since we are not using authentication at this point (although this would be easy to use with this logic as well!) we need a way to persist the cart of a user, and we can do it like this:
- If a user opens the app, we check the Capacitor storage for a value stored under our
CART_STORAGE_KEY
- If there is no stored value, we start a new cart by creating a document inside the Firestore collection. We will then use the ID of this new document and store it locally, so we can later retrieve the cart of a user again!
- If the app starts and we find this ID already, we access the cart document from Firestore and load all the stored values/amounts!
With this approach we update our local cart data and also keep track of all the items inside a Firebase document.
Again: With authentication, you could simply use the unique user id to have a connection between user and cart instead of using the random id generated by Firebase right now.
We can also already create the getProducts()
function which returns our product data including the actual ID of the document, and keep track of our cart by using a BehaviorSubject
that always holds the ids of items added and the amount.
Get started with our service by changing the services/product.service.ts to:
You might have noticed the INCREMENT
and DECREMENT
at the top already – these are super helpful functions from Firebase to easily change a value. In our case, we use it to increase/decrease the amount of an item inside our shopping cart and also inside the actual products collection, since we need to change the stock of a product at the same time!
We can now also use a computed property by using brackets around the id, which uses the value of the ID as the property name!
That means, once we add items to the cart, the document inside Firebase looks something like this:
So we use the ID as a key in the object, and the value is the amount in our cart.
Go ahead and add the following to the same services/product.service.ts now:
At last we also have a simple checkout function which writes the current cart to another orders collection and clears our cart by using the set()
function which will replace the whole document to the new value (before we only used update()
!).
Building the Shopping List
Before we now dive into the product list, let’s quickly already import the module of the cart page that we generated in the beginning since we will later open the modal from this page.
Open the src/app/home/home.module.ts and import it like this:
Now we can retrieve the products from our service and assign it to an Observable to which we will subscribe from our view in the next step so we don’t need to manage it inside our class at this point.
We will also subscribe to any changes of the cart so we can set the value in our class to the new value of the cart, which will help to display the amount of an item inside our view,
As a little bonus, I also added an Ionic animation which we simply create once upfront and then call play()
whenever we add or remove items from our cart.
Finally those functions simply call the according service functionality – everything is handled in there, and also the cart updated will be received automatically so we don’t need to worry about the state of our data!
Go ahead and change the src/app/home/home.page.ts to:
In our functions we also have stopPropagation()
because they are triggered from buttons inside an ion-item
which has a click handler itself to expand a read more section.
By passing the event to those functions and stopping it right there, we make sure that the parent click event isn’t also executed. Nice and easy hack that comes in helpful every now and then!
Inside the template we can now subscribe to the products Observable using the async
pipe to handle all the subscription automatically. Additionally we display a bit of the information from a product like the image, stock and the expandable section with a super simple click logic.
At the bottom we keep our fab button with the #myfab
template reference – remember how we used that for our Ionic animation before?
Inside the product we can now access the cart
object and check if the ID of a product is included and display the value (or 0 as fallback) and also use this logic to disable a remove button. Nobody wants -1 items in their cart!
Now open the src/app/home/home.page.html and change it to:
Now we already got a nice list of product items in place and can wrap up everything with a quick checkout view.
Adding the Checkout Page
This page is quick to add, but we need our brain one more time to implement a logic which:
- Loads all product information
- Checks if a product of our cart exists in that data
- Combines the product data and the value for each product we have in our cart
In reality you could also do it the other way and load the Firebase data for each item inside your cart. Really depends on how many products you actually got and which operation would take longer.
To create a nice array with all of that information for the checkout page we load the products once using the take(1)
operator.
We then filter()
out all products that don’t exist inside our cart, and finally we map each product to a new value that now combines information using the ...
spread operator so we got the actual product and the count
in one object!
Additionally we can add the code for the checkout which uses the function of our service and closes the modal with a little alert for testing.
Now open the src/app/cart-modal/cart-modal.page.ts and change it to:
The last step is to create another simple view to list all of the items with their count inside the cart and add a checkout button inside our src/app/cart-modal/cart-modal.page.html:
We will not dive into the creation of a checkout form and payment logic but you can find courses on those topics inside the Ionic Academy!
Automatically clear Cart after X Minutes?
Right now we reduce the stock for products whenever we add them to the cart, but what happens if a user doesn’t finish the checkout?
To fix that problem, I recommend you create a CRON job with Firebase cloud functions and simply iterate the cart collection inside that function.
Because we keep a server timestamp of the last update in each cart document you can easily check when a cart was last changed.
If it’s too long ago, simply use the keys inside the cart to once again increment the stock of each product and then clear the cart in the background with this logic!
Conclusion
It’s possible to build an Ionic E-Commerce shop based on Firebase with a lot of the Firebase benefits! You can manually upload all your products with a script (or build your own admin area), and you can keep the cart of a user inside the Firestore database as well with a nice sync to your actual Ionic app.
If you want to see more about this topic, leave a comment below!
You can also find a video version of this tutorial below.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK