How I Created My Own Stock Index Tracker with Time-Series Charts using Low-Code
12
January
2022
Tutorial

How I Created My Own Stock Index Tracker with Time-Series Charts using Low-Code

How I Created My Own Stock Index Tracker with Time-Series Charts using Low-Code
Vihar Kurama
0
 minutes ↗
#
dashboard
#
admin
#
beginners
#
automation
#
code
Tutorial

I recently started investing and came across a product called Smallcase. The way it works is — experts create a diversified long-term portfolio of stocks & ETFs and manage it on a timely basis for you. I really love the idea of how stocks can be added into portfolios or baskets to reduce market volatility. Unfortunately, at the moment, this product is only available for Indian investors and that led me to create an app, where I could create a portfolio, and also create a custom index on top of it, with features to compare benchmarked indices like Dow Jones / S and P.

Building this kind of application from scratch would have taken me a lot of time; I would have had to choose a front-end framework, configure a database, and work on different visualizing frameworks to build time-series charts. With Appsmith, I was able to build this app in just a few hours. If you don’t already know, Appsmith is an open-source low code framework to build internal apps. In this blog, I will take you through the steps I followed to create the app.

First, let me share the specs of the app in a little more detail.

With this application, you can do the following:

  1. Track stocks: Set filters on what stocks should be tracked, throughout the day by default or create specific lists.
  2. Make your own baskets: Create customized stock portfolios as baskets.
  3. Time-series charts to compare performances: Create a custom index for these portfolios and compare them with benchmark indexes using time-series charts.
  4. Notify: Send notifications and triggers when there are fluctuations in the market.

In this blog, I will also dive into building some nifty time-series charts and build our stock index tracker that can compare with S&P 500, Dow Jones, and NASDAQ.

Here are a few screenshots of the application:

Screenshot of Custom Index Tracker on Appsmith
Screenshot of Custom Index Tracker on Appsmith — 2

Now, let’s get started!

What All Did I Use to Build This Application?

TLDR; I’ve used Appsmith, Fusion Charts on Appsmith, APIs from MarketStack, Alphavantage, and Google Sheets as the backend to build this application.

This application primarily uses Appsmith, an open-source low-code tool that can connect to any database, API, or GraphQL to build admin panels, dashboards, and internal tools. Appsmith also supports charting options; it has an in-built extension that uses Fusion Charts to create data visualizations; this made it much easier to build my own time-series charts. To pull all the stock data and prices in real-time, I’ve utilized free APIs from MarketStack and Alphavantage.

(Please remember to generate your own API keys if you’re following this tutorial to build a similar app! To know more about generating your own API keys, read this blog)

I’ve used Google Sheets as my backend to watchlist stocks and store customized stock portfolios and baskets.

Creating Baskets to Group and Track Stocks

The first step to creating portfolios, or as I like to call them, “baskets,” is to build a user interface. Through this, a form can take in our portfolio name, time created, and a logo for easy viewing… and some vanity! 😎

It took me less than 5 minutes to create this with Appsmith and Google Sheets; here’s how I did it:

Note: I’ve used the Cloud Version (Community Edition, which is free) of Appsmith; you can build this either on a local version using Docker or a self-hosted version of Appsmith.

  • Sign-up for a new free account on appsmith.com
  • Click on the + icon next to Datasources and choose Google Sheets as Datasource.
  • Authorize your Google Account, and create a new query by hitting the NEW API button after the data source is saved.
  • Renamed the query name to assBasket, as we’ll need to access query names on the UI.
  • I created a new google sheet with the following columns:

Basket Name
Basket Image URL
Basket Create On

  • Copied the URL of google sheets and pasted it under the SpreadSheet URL property.
  • Set the Query Type to Insert Sheet Row

With this, our query is ready. Next, to build UI on Appsmith, you can just drag and drop widgets from the library on the right side of the screen. Appsmith’s canvas is quite responsive, and you can even drag widgets between two other widgets, and it will auto-resize, saving you valuable time! I added a container widget so that our app looks unified; we even have an option to add colors to this if we want to stylize the background a little more. I then dropped a text widget to set the app’s name and a button widget.

Here’s how it looks:

Image by Author | Screenshot of Page 1 Custom Index Tracker

Neat, yeah?

Next, since we want there to be a form to create new baskets, we should get the button to open a modal. To do this, click the settings icon on the button widget to see the property pane.

Property pane is where we can configure all the properties of the widgets. You can open this, by simply clicking on the widget, and you’ll see it docked on the right sidebar, just as shown in the above screenshot.

We need to update the onClick property of the button and set it to open a new modal. You can create it there or drag and drop a modal widget onto the canvas. Both options work. You do you.

Next, we need three types of inputs for the form, so I added three input widgets to this modal. You can set the labels as follows:

Basket Name
Basket Image URL
Basket Create On

Here’s a Loom on how it looks like:

Things look in great shape so far, in order to be able to track the index of the portfolios based on created time, I thought it was best to use a pre-installed library on Appsmith since it’s not possible to track this manually. I used moment.js to do this.

We can set the Basket Created On default value to:

{{moment().format(“MM ddd, YYYY HH:mm:ss a”)}}

This will save time when the portfolio is created.

On Appmsith, we can write JS anywhere across the platform to add customization using the moustache {{ }} bindings. It also comes with the moment.js library; hence, calling the function will save time when these portfolios are created.

Lastly, I opened the buttons property-pane and set the onClick property to run a query and choose addBasket query.

With this, my UI is all set; lastly, I went back to addBasket query and set the Row Object to the following:

{ "Basket Name":{{Input1.text}},
"Basket Image URL": {{Input2.text}},
"Basket Create On": {{Input3.text}}
}

Note that we will be collecting the values from the Input widgets and passing them to the Google Sheets via the addBasket query.

Next, to display all our baskets on this page, we need to create a new API. I created another one called getBasket, from the Google Sheets datasource. I updated the query method to Fetch sheet row list everything from the excel sheet. Here’s a screenshot:

Screenshot of getBasket query

Next, we have to bind our queries to the UI widgets. This part can be done like this:

  • Open the property pane of List1 widget, and set the Items to {{getBasket.data}}
  • Inside the list widget, select the image and set the image property to {{currentItem[“Basket Image URL”]}}
  • Set the text widget properties to {{currentItem[“Basket Name”]}}, and Basket Created On: {{currentItem[“Basket Create On”]}}

This is how it looks now:

Screenshot of getBasket query

Here’s what we’ve been able to do till now:

  • Added functionalities to add a new portfolio/basket and list them on Appsmith.

Now, we will work on adding stocks inside these portfolios. For this, it would be best to create a new page to search for stocks and add them to baskets.

Let’s create a new page; you can choose the option on the left sidebar and name it as ‘Basket Page’. The idea is to redirect to this page from Page1 and filter all the stocks present in the basket.

But how do we filter stocks? Usually, we do on a regular backed to consider an id and filter based on it. Similarly, on Appsmith, while navigating to Basket Page, I stored the value of the basket page to filter and display data on the Basket page.

I can use the code snippet I mentioned below on a new button widget placed on the list widget. So, when clicked, it should save the selected item on the list, redirect to the basket page, and filter accordingly.

We need to the button’s onClick property to:

{{(function () {
    storeValue("selectedBasket", List1.selectedItem["Basket Name"]);
    navigateTo("Basket Page") })() 
}}

Here, we need to use the storeValue from Appsmith to store the basket name in a variable named selectedBasket, the List1.selectedItem copies the data from the selected list item.

Next, we need to use the navigateTo function to redirect to a new page.

Adding Stocks into Baskets

Before we add any stocks into our portfolios, we’ll have to ensure that this page filters my stocks according to the selected basked from page one. So let’s add a container and a text widget to display the Basket name.

Note that this value comes from the global store, so on the Text property from Text widget’s property pane, we will have to bind value from the Appsmith store, and this can be done with a simple line:

{{appsmith.store.selectedBasket}}

Alright, the next cool feature for us to add is a search function. This way, we can easily search for stocks and add them to baskets; for this, we need to add another button and modal with the following fields:

  • An input widget
  • A button labbeld as Seach
  • A table widget to list out all the results
  • A select widget to add them to the list of baskets I created

The table widget definitely deserves high praise. It allows us to add filters and sort results. We can add relevant stocks based on where they are listed on. For example, I could simply search NASDAQ, which filters stocks listed there. If you want to know everything that you can do with a table widget, you’ve got to check out this detailed blog.

Before I tell you how I built this, here is how it looks like:

Screenshot of Basket Page UI

The search feature works with a simple API from Stockdata, to integrate this, I followed the following steps:

  • Click on the + icon next to the Datasources
  • Select Create New API, and paste the following URL:

https://api.stockdata.org/v1/entity/search?search={{stockcode.text}}&api_token=YOUR_API_HERE

  • Rename the API query to stockSearch

To get this working, make sure you add API token from Stockcode here. Please note that I use moustache bindings here. This adds the values I’m searching for from the input widget dynamically. Now, let’s head back to the modal and update the names of the widgets.

I renamed the widget names to the following, to make it easy while pushing data onto sheets:

Input Widget: stockcode

Table Widget: stockSearchTable

Now, the search API takes the value from the input widget, and on the table widget, we can bind the results from the API for the following functionalities:

  • Set the buttons onClick property to run a query and choose stockSearch query.
  • Bind the stockSearch query to the table widget, using {{ stockSearch.data }}

Next, we want to select which basket we want to add the searched stock to; for this, I just copied my API (getBaskets) from Page1, and bound it onto the selected widget with the following code:

{{
    getBaskets.data.map((row) =>   
    {
    return {
    		label: row["Basket Name"],
        value: row["Basket Name"]    
     }  })
 }}

Last, we need to save all this information onto a Google Sheet, so let’s create a new spreadsheet under the same Google Sheet and create a new API from the connected data source. I named this sheet Watchlisted Stocks and named the query addtoBasket.

These are the columns I have on my Google Sheet:

symbol
name
type
exchange
exchange_long
mic_code
country
watch_listed_on
basket

Now, on the query to collect all this information, we have to update the Row Object to the following:


{"symbol": "{{stockSearchTable.selectedRow.symbol}}","name":"{{stockSearchTable.selectedRow.name}}","type":"{{stockSearchTable.selectedRow.type}}","exchange":"{{stockSearchTable.selectedRow.exchange}}","exchange_long": "{{stockSearchTable.selectedRow.exchange_long}}","mic_code": "{{stockSearchTable.selectedRow.mic_code}}","country":"{{stockSearchTable.selectedRow.country}}","watch_listed_on": {{moment().format('MMMM Do YYYY, h:mm:ss a')}} ,"basket": {{Select1.selectedOptionValue}}}

With this last step, our watchlist will be ready. However, in order to show it on the page, we have to add a new table widget. Wait, I still had to pull all the watchlisted stocks from the google sheets. This is pretty straightforward, I create a new query from the GSheets datasource, set the method to Fetch Sheets Row, copy my GSheets URL, and update my Sheet Name to Watchlisted Stocks.

Now, we have to bind it on the new table widget, but here, it should only filter stocks that are added to this basket or portfolio, I do this by using a simple transforming when binding using the following code snippet:


{{     
    getStocksfromBaskets.data.filter((item) => {
    return item.basket == appsmith.store.selectedBasket
    })
 }}

As you can see, we’re now filtering our stocks based on the selectedBasket value from the Appsmith store that we saved while redirecting!

We now have all the portfolios and stocks ready.
Now it’s time for data visualization!

Building Time Series Charts and Tracking Index

As mentioned, Appsmith’s chart widget comes with the Fusion Chart configuration, which makes it much easier to build time-series charts. The other thing I love about this is, I can even create candlestick charts for the stocks I watchlisted inside the application. These charts are used by traders to determine possible price movement based on past patterns.

First, let me show you how to fetch details of all the stock prices, using the MarketStack API:

  • Inside the basket page, I created a new API (marketStackAPI), with the following URL:

http://api.marketstack.com/v1/eod?access_key=YOUR_API_KEY&symbols={{appsmith.store.current}}&date_from=2021-11-01&date_to=2021-12-12

Note: I’m filtering the data from 2020–11–01 to 2021–12–12, you can update this API accordingly based on your requirements.

In the API, as you can see, I have added an Appsmith store variable named current; this is to dynamically fetch the stock prices of the symbol or stock we wanted to analyze or add to our tracker.

Now, we need to write a code snippet under JS Objects, that stores all the data for all the stocks that are there inside my portfolio.

This is what I’ve used:

export default {

getBasketGraph: () => {let stocks = getStocksfromBaskets.data.filter((item) => item.basket == appsmith.store.selectedBasket)    let stockcodes = stocks.map(item => item.symbol)    let allStockData = [];    stockcodes.map((item, index)=> {    storeValue("current", item);     marketStackAPI.run(()=> {     let tempData = marketStackAPI.data;     allStockData.push(tempData.data);    }, () => {}, { allStockData });  })    storeValue("allStockData”, allStockData)    return appsmith.store.allStockData; 
}}

Here is what this code snippet does:

  • Stores all the symbols that are present in the basket in the stockcodes variable
  • Iterates through the stockcodes array and stores all the stock prices in a new variable allStockData
  • Returns the store variable when the function is executed

To create a time series chart, we need to drag and drop a new chart widget onto the canvas, below the table widget.

This is how it looks like:

Image by Author | Chart Widget on Appsmith

It comes with a default configuration, so we will have to change the type to a Custom Chart to configure our data onto this. We will need to follow a particular format in order to do this. Here’s the basic config for Fusion Charts:

{  "type": "",  "dataSource": {    "chart": { },    "data": [ ]  }}

Here, we need to pass in three parameters, the chart configuration, data, and the categories that need to be displayed on the x-axis. Here’s the updated code:


{    "type": "MultiAxisLine",    "dataSource": {        "chart": {            "xaxisname": "Date",            "vdivlinealpha": "",            "labeldisplay": "ROTATE",            "theme": "fusion"        },        "categories": [{                "category": {                    {                        marketStackAPI.data.data.reverse().map((row, index) => {                            return {                                "label": moment(row.date).format("LL"),                            }                        })}                }            }        ],        "axis": [{                "title": "Price",                "dataset": [{                        "seriesname": "Apple",                        "data": {                            {                                marketStackAPI.data.data.map((row, index) => {                                    return {                                        "value": row.close,                                    }                                })}                        }                    },                }            ]        }    }

Finally, this is how our graph will look like with the aforementioned configurations:

Image by Author | Charts from Custom Index

Additionally, I also created a list, that tells us the index value with simple math:

Image by Author | Custom Index and Predictions with Simple Math

Imagine having your own custom app terminal to track all your stock indexes in one place. If you’re into crypto, you can extend this app to even have a crypto tracker.

I hope that you had success following this tutorial and building your own app. If you got stuck somewhere, I’d be happy to help you out :)

More content at plainenglish.io. Sign up for our free weekly newsletter. Get exclusive access to writing opportunities and advice in our community Discord.

Appsmith Basics: How to Query Databases and Bind Data to Widgets
3
December
2021
Tutorial

Appsmith Basics: How to Query Databases and Bind Data to Widgets

Appsmith Basics: How to Query Databases and Bind Data to Widgets
Confidence Okoghenun
0
 minutes ↗
#
admin
#
beginners
Tutorial

Every application involves some level of CRUD operations, be it reading records from a database, creating or updating records, or deleting records. All of which is put together by well-designed application UI and logic.

In this article, I will show you how to build a task manager in Appsmith using Firestore as the database. By doing this, we will cover and solidify core concepts like connecting to databases, writing queries, infusing data to widgets, and writing custom functionality using JavaScript.

In this article, you will learn how to do the following:

  1. Connecting to and querying Firestore
  2. Binding data to widgets on Appsmith
  3. Deploying the application you built

Let’s get started with the first.

1. Connecting to and querying Firestore

Before we go in-depth into using Firestore, you need to create an app. Signup for Appsmith cloud and click on the New button with orange. Now, we can connect the created app to the database.

Click on Datasources > Create New and then Firestore. Fill in the credentials to connect to your firebase instance. To make sure all details are correct, click on the Test button, after which you can save the data source.

To get your Service Account Credentials, go to your project settings in Firebase and generate a new Nodejs private key that will be copy-pasted into your Appsmith app.

Here’s a snapshot of my setup:

my Firestore configuration

Using the Firestore data source, we need to query for data. Let’s write a query to get tasks from the database. To display some data, I have a simple collection called asana that has some seeded data. A query to get tasks would look like this:

query to get tasks from database
The response data in the snapshot above shows the shape of each entry in the database. This will be useful in seeding your database.

Now that we have linked to Firestore and have some data coming in, let’s display that data in the app using widgets.

2. Binding data to widgets

To display the data coming in, we’ll need a List widget. Switch to the widget tab in the sidebar and drag a List widget into the canvas. (The widgets tab is below the app name)

widgets tab

On the List widget, a simple binding can be written like this:

binding data into the list widget

Similarly, we can display the data for each item in the List widget by bringing in Text widgets and writing their corresponding bindings.

displaying data in the list

That’s all you need to know about binding data to widgets; write {{}}, and you’re good to go.

Before we move on to deploying the app, let’s spend a few minutes building a form that will allow us to update/delete tasks.

To do this, drag in a Form widget into the canvas, and use a couple of text widgets to display the information about the task selected from the List widget, such as clicking on a new item on the list will automatically update the form. Your binding should look like this:

binding to display selected item from list

You should also do the same for the Datepicker, Input, and Select widgets required to build the form. For example, you should configure the selected widget this way:

![select widget configuration] (res.cloudinary.com/confidenceappsmith/image..)

You should also rename your widget to something more descriptive as I did in the Select widget shown above

Now, using the Firestore datasource configured earlier, you can write an update query like this.

query to update a task

And then, configure the submit button on the form to call the update_task query when clicked.

running update query on submit button click

Wasn’t that was quite easy? Using the same principles, you can write a query to delete the task.

3. Deploying the application

This is by far the easiest step. To deploy an app, click on the Deploy button to the top right corner of the screen.

You may also invite others to use/develop the app or even make it publicly available. You can use the share button just beside the Deploy button. This brings up a modal:

share button modal

Wrap up

you made it

You’ve made it! You’ve learned the core concepts of building apps with Appsmith, and I’m sure you’re ready to put this knowledge to use.

I’m going to leave a link to the app here with more features added to make it production ready. Click on this text to see the app.

Awesome! Go into the world and build! (Also consider giving us a star on GitHub)

If you have specific questions for me, just send me an email and I’ll be happy to help!

The Modern Stack to Build Internal Tools: Supabase, Appsmith, n8n
8
November
2021
Resources

The Modern Stack to Build Internal Tools: Supabase, Appsmith, n8n

The Modern Stack to Build Internal Tools: Supabase, Appsmith, n8n
Vihar Kurama
0
 minutes ↗
#
applications
#
community
#
crud
#
automation
#
beginners
Resources

Developers spend quite a bit of time building internal tools, admin panels, and applications for back-office tasks that help automate everyday essential business processes. These involve multiple efforts, from maintaining a special database to writing lots of frontend and backend code. But, what if we told you that you could utilize a modern stack to build such applications that can help with your backend, frontend and automation tasks? Sounds good right? It is!

We’re happy to introduce a great new stack to build applications: The Supabase, Appsmith and n8n stack (SAN Stack) for developers to build and maintain modern custom internal tools.

What is the SAN Stack?

SAN stands for Supabase, Appsmith and n8n, after the three emerging and notable software that makes up the stack.

Supabase: The open-source firebase alternative to creating a backend in minutes. Start your project with a Postgres database, authentication, instant APIs, real-time subscriptions and storage.

Appsmith: An open-source framework to build custom business software with pre-built UI widgets that connect to any data source, and can be controlled extensively using JavaScript.

n8n: An extendable workflow automation tool. With a fair-code distribution model, n8n will always have visible source code, be available to self-host, and allow you to add your custom functions, logic and apps.

This stack lets you build any application within minutes. You can use Supabase for the database and backend, Appsmith for UI and adding functionality, and n8n for automating background tasks.

One of Appsmith’s co-founders and head of product, Nikhil Nandagopal broke down the basics of app building into three steps.

CleanShot 2021-11-08 at 11.20.37@2x.png

This has gained quite some traction among developers, especially those looking to build internal tools or applications.

Why Supabase, Appsmith, and n8n?

  • Free / Opensource: Supabase and Appsmith are fully open-sourced and can be self-hosted on their servers. While n8n follows a fair-code distribution model and always has visible source code, which is available to self-host.
  • Low-code yet high functionality: All three platforms follow the principles of the low-code model to help developers deploy and scale their applications in the fastest way possible. However, devs can utilize SQL, JavaScript, and data structures to customize their applications.
  • Editing Experience: Supabase, Appsmith, and n8n have an excellent UI interface and provide rich editing and debugging experience for developers right from the beginning. Both Appsmith and n8n provide a drag and drop interface for building UI and automation workflows, respectively. In comparison, Supabase offers a live SQL editor to test out and play with your database and has the power to export them into APIs directly from the platform.
  • Collaboration: When working with teams, all three platforms offer great collaboration tools; you can share these applications or workflows with anyone and set specific permissions such as view-only or edit mode. They are consistently being improved in their future roadmap.
  • Self-hosted: Developers can self-host all three platforms on their servers for free. It is useful when you want your data to be more secure, have complete control over customization, and have custom domain options.
  • Fantastic Community: The community is incredible across all three platforms; they provide excellent support and a transparency roadmap. New feature requests or existing bugs are immediately taken care of based on the priority. And with a great community, content gets better and better, and they provide rich documentation and many tutorials for devs to get started.

Build a Simple Ticket Manager Using SAN Stack

There are so many tools and applications that can be built across the SAN stack. Here are a couple of examples: An Employee Survey Dashboard and a Ticket Management Admin panel.

Using the SAN stack, you can build any dashboard in just minutes.

As an example, I will show you how to create a support dashboard manager application.

Using this application:

  • Users will be able to create or raise new tickets for a particular query
  • The support team will be able to see these tickets and assign them to engineers
  • When the tickets are resolved, we will be sending an automated email to the users
CleanShot 2021-11-08 at 12.20.33@2x.png

Let's get started!

Set up your Backend on Supabase

The first step is to set up the backend for the application; for this, we will be using a Postgres database on Supabase.

  1. If you are new to Supabase, you can create a new account (it's free!) or sign in with your existing credentials.
  2. You will be redirected to the Supabase dashboard; here, you can manage all your projects.
  3. Create a new project, and set the name to Support Dashboard. Create a new table by clicking on the Create Table option on the side navigation.
  4. Supabase gives us many ways to add data to the tables, from writing queries to creating schemas using UI to simply uploading CSV files; developers can choose any option.
  5. For our support dashboard, we will be creating a table by uploading a CSV file on Supabase.
CleanShot 2021-11-08 at 12.21.48@2x.png

The DB is now set up; let's use Appsmith to connect this PostgresDB and build UI for the application. For this, we might need to note down the connection info from project settings on Supabase. Following is how it looks like:

CleanShot 2021-11-08 at 12.22.58@2x.png

Build UI on Appsmith and Writing Queries

Our backend is ready; now, let's connect it to Appsmith to build UI and add functionalities. Follow the below steps:

  1. If you are new to Appsmith, you can create a new account (it's free!) or sign in with your existing credentials.
  2. After we sign in, we will be redirected to a dashboard to create a new application.
  3. Next, let's connect a new data source. To do this, click on the + icon next to the Datasources from the sidebar and choose PostgresDB.
  4. Now, copy the database connection details from Supabase to here and click on the test button to validate the authentication.
CleanShot 2021-11-08 at 12.23.58@2x.png

Awesome, we now have established a connection to our data source. Next, let’s build UI using widgets on Appsmith.

  • Click on the + icon next to widgets and drag and drop a Tab widget. We can configure using the property pane by clicking on the cog icon on the top-right corner.
  • As seen in the below screenshot, we have added four tabs to support the dashboard.
CleanShot 2021-11-08 at 12.24.46@2x.png
  • Now, we will add a button that should open a modal and have a form to raise a new ticket when clicked. For this, just drag and drop a new button widget from the widgets section and move it on canvas.
  • Add a few input widgets and a button to submit the form; this is how the form looks after the UI is complete:
CleanShot 2021-11-08 at 12.25.29@2x.png
  • We now have the UI to create a ticket. Let’s write two queries on Appsmith that will allow us to create tickets and list tickets. To do this, click on the + icon next to the data sources and use the Supabase connection here to create a new query.
  • Rename the query to create_new_ticket under the query pane; here we can write SQL that can collect inputs using moustache bindings. Following is how it looks like:
INSERT INTO PUBLIC."tickets"("id","createdAt","user","updatedAt","description",
"status","priority","category","assignedTo")
VALUES('{{appsmith.store.ticket.id}}','{{moment().format('yyyy-mm-ddHH:MM:ss')}}','{{c_user.text}}', 
'{{moment().format('yyyy-mm-ddHH:MM:ss')}}','{{c_description.text}}','{{c_status.selectedOptionValue}}',
'{{c_proporty.selectedOptionValue}}',
'{{c_category.selectedOptionValue}}','{{c_assignee.selectedOptionValue}}');
On Appsmith, we can use moustache bindings anywhere across the app to bind data or write javascript code to customize and add functionalities to your widgets.
  • Lastly, we now set the onClick property for the button to execute a query and select the create_new_ticket. And just like that, we should be able to create new tickets on the application.
  • Now, let’s write one more query where we could list all the tickets that users create. We will name this query get_tickets; the following is the SQL snippet.
SELECT * FROM public."tickets";
  • Now, drag and drop a table widget onto the tab widget under the Assigned To Me tab. Open the property pane and add the following snippet to bind the tickets:
{{get_tickets.data.filter(t => t.assignedTo === 'confidence@appsmith.com' && t.status !== 'closed')}}

Fantastic, we should be able to see all the tickets assigned to the specific user! It’s that’s simple to write custom JS to configure our internal applications on Appsmith. Now let’s use a webhook and build automation that sends Emails from the ticket using n8n!

Building an Extendable Workflow on n8n

If you want to build an internal tool that requires sending emails, then n8n is the way to go. n8n is a tool that can be used to automate workflows between your favorite web apps (such as Slack, Google Drive, Dropbox, etc.). However, n8n can be used to connect almost any two web apps that you use. Now, let's create a workflow and use a webhook to send requests to n8n from Appsmith.

  • If you are new to n8n, sing-up for their cloud version here.
  • Next, create a new workflow by selecting New under the workflow menu
  • Now, drag and drop a Webhook node onto the canvas; you can configure the nodes by clicking on them.
  • Now set the HTTP method to POST and copy the TEST URL

Awesome, now that we have the Webhook, let’s connect it with Appsmith by adding it as a data source.

  • On the appsmith application, click on the + icon next to the data source and create a new API.
  • Set the API type to POST and paste the API webhook URL,
  • Now paste the following code snippet under the body tab to collect input from the dashboard.
{"message": "({this. params. message})","email": (this. params. email})","ticket": "((appsmith. store. ticket. id}}"}
  • Next, connect a Gmail node to the webhook and authenticate with your Google ID.
  • To pass the data from the webhook to the Gmail node, configure the message property by using the variable selector nodes on the left pane.
  • Lastly, make sure you set the workflow state to active.

And just like that, we should be able to send Emails using n8n without writing any piece of code.

CleanShot 2021-11-08 at 12.28.38@2x.png

Building this app from scratch, including writing snippets of code, is likely to take 30 minutes! Isn’t that fast?

If you're looking for a modern approach to building internal applications, check out Supabase, Appsmith, and n8n! These tools are straightforward, powerful, and can help you build apps faster than ever. So what are you waiting for? Start building your next internal app today.

Our New JS Snippets Feature Helps You Write JavaScript in the Appsmith Platform
18
October
2021
Announcement

Our New JS Snippets Feature Helps You Write JavaScript in the Appsmith Platform

Our New JS Snippets Feature Helps You Write JavaScript in the Appsmith Platform
Vihar Kurama
0
 minutes ↗
#
announcement
#
beginners
#
applications
#
app-development
#
features
Announcement

Building an app on Appsmith is great fun. Why? Because it takes minutes to build a clean and consistent UI, and less than a few hours to make data connections.  We might be tooting our own horn, but what we love about Appsmith (ask our in house devs!) is that we can use JavaScript anywhere on the platform to add additional transformations, functionalities, and actions using the moustache syntax. We’re aware that not everyone is a JavaScript enthusiast, everyone prefers a language of their choice! So we’ve come up with our new feature: “JS Snippets.” With this, you can get some help with writing JavaScript inside Appsmith. In this blog, I will tell you how we made this feature and how you can use it!

The story!

We often see many questions in our community forums and discord channels seeking help with binding nested APIs, write data transformations, configure chained actions. Hence, we thought of building a library of snippets inside Appsmith applications that you can use directly and customize based on your data source. 

Initially, we thought of the issue in a straightforward way, but at Appsmith, we always like to go the extra mile. So, we brainstormed this idea multiple times and decided to extend it to customize and add snippets particular to widgets and data sources. But, in order to do this kind of customization, we need a database application that validates and filters these snippets. So we built an internal Appsmith app that manages all the JS Snippets. This is how the application looks like:

Here, as we can see, on the left, we see a list of all the available snippets today. When these are clicked, we will see the details of the snippet and have options to verify it and publish it live directly to the JS Snippets library.

To customise these snippets, we define three formats for each of them. 

  1. Snippet: The example code snippet written in JS
  2. Args: Customisable variables inside the snippets and their expected data type,
  3. Template: The dynamic template that helps devs customise their snippet with any variable on Appsmith

Here’s an example of how we ideated customizable JS snippet using these three forms for merging two queries in a table:

Snippet:

{{ 
	fetchOrders.data.map((orderObj) => {
   const user = fetchUsers.data.find((userObj) => userObj.id == orderObj.refId) || {};
   return { ...orderObj, ...user };
	})
	}
}

Args:

[
  {
    "identifier": "fetchOrders",
    "name": "Query1",
    "type": "OBJECT"
  },
  {
    "identifier": "fetchUsers",
    "name": "Query2",
    "type": "OBJECT"
  },
  {
    "identifier": "orderObj",
    "name": "row1",
    "placeholder": true,
    "type": "OBJECT"
  },
  {
    "identifier": "userObj",
    "name": "row2",
    "placeholder": true,
    "type": "OBJECT"
  },
  {
    "identifier": "id",
    "name": "key1",
    "type": "VAR"
  },
  {
    "identifier": "refId",
    "name": "key2",
    "type": "VAR"
  },
  {
    "identifier": "user",
    "name": "recordForMerge",
    "placeholder": true,
    "type": "VAR"
  }
]

Here’s a screenshot of how the snippet is rendered on Appsmith:

Users can now directly copy this snippet onto the widget, or customize the arguments, test it out, and use it in the widget.

How to use JS Snippets on Appsmith

We can find JS snippets inside the Appsmith applications from Omnibar. Click on the Search/Omnibar from the top navigation and choose the `Use snippets` option. Here, you can filter snippets based on data sources and UI widgets. 

The other easy way is to access snippets from the slash commands. Just type in / inside the bindings, and choose the insert snippet option. 

Special credits to Arun Vijayan, Sumit Kumar, Ajinkya, and Nikhil Nandagopal who had worked so hard on this feature!

Hope you’ll build some super cool applications using the JS Snippets on Appsmith! If you do, don’t forget to tell us about it, we would love to feature your work! Your contributions and feedback help us make Appsmith better and we really appreciate it.

Join the community! Come chat with us on Discord, or jump in on Github directly!

You can also follow us on Twitter and Linkedin.

Coding Practices Your Future Self Will Love You For
18
September
2019

Coding Practices Your Future Self Will Love You For

Coding Practices Your Future Self Will Love You For
Arpit Mohan
0
 minutes ↗
#
career
#
beginners
#
Coding
"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."
    Martin Golding

Here are 6 coding practices that I've adopted in the past 10 years to ensure that my future self has fewer sins to forgive.

1. Standardize code formatting

Any codebase is read a lot more than it is written. Code with consistent formatting is easily readable and comprehensible for everyone in the team. Standard formatting ensures that your eye, and your subconscious, can look for variables, braces, functions, etc seamlessly. Golang does a great job by providing the gofmt command in the standard library. This ended all formatting discussions that come up so often in code reviews in the Golang community.

2. Don't follow the DRY principle blindly

DRY (Don't Repeat Yourself) is almost a mantra for developers. But if applied indiscriminately, it leads to abstract code that’s hard to read & understand. It also stops different parts of the code to evolve to their full potential. Do not follow the DRY principle blindly.

It is a good idea to copy-paste the same function a minimum two times in the codebase. Only when you see the same requirement a third time, should you refactor the code and apply DRY. Doing this ensures that you are not prematurely assuming that two problems that looked the same initially, are still going to remain the same after a period of time. When you come across a similar requirement a third time, you have some data on what parts of the code are common. You also have three instances of repeated code to create a good abstraction.

3. Debug code via logs

Practice debugging code on your local machine via logs instead of a debugger. Debugging on your local machine ensures that logs are added at the right place. This, in turn, makes sure that you can debug production issues quickly because you would have gone through this cycle on your local machine before. Remember to not get too excited and add unnecessary logs everywhere. It will clutter your log file in production.

Too much logging == no logging.

4. Beware of premature optimizations

A primary goal of code optimisation is to improve performance. More often than not, performance issues are not where you think they are. Always benchmark your code before starting to optimize for performance. Without benchmarking, how will you ever know whether the code changes you make have any real impact on efficiency or not? Premature optimization, especially micro-optimization, is not a good idea because you don’t know whether you are working on removing a performance bottle-neck or not.

As a corollary, this doesn't give you the license to code like the wild west. Don't get the computer to do work that it doesn’t need to do just because you got lazy and didn't think of the most efficient way of solving a problem.

5. Don't complicate your codebase with unnecessary features

Don’t complicate the codebase with features that no user has asked for. This is a problem you need to avoid in early product lifecycles. Startup teams tend to assume that building more features will help them find product-market fit faster. This is an anti-pattern. Adding unnecessary features makes the code harder to read & debug. When new developers come on board, they will find it difficult to differentiate important code paths from the ones that were added on a whim. Eventually this technical debt slows the entire team down.

6. Setup a CI/CD pipeline early in the development lifecycle

Even if it’s a one-wo/man show, a CI/CD pipeline reduces the overhead of remembering (& doing) the build & deployment of a particular codebase. The common assumption is that CI/CD pipelines are important only in teams that are pushing a lot of code into production every day. In my experience, CI/CD pipelines are even more important for codebases that are rarely touched because you won’t remember how & where the code was deployed. This is especially true if you are updating the code only once a year. Plus, having a CI/CD pipeline ensures that you have a version-controlled script telling you exactly what you were thinking X months ago.

5 Tips for Beginners to Learn Better and Stay Motivated
5
September
2019
Engineering

5 Tips for Beginners to Learn Better and Stay Motivated

5 Tips for Beginners to Learn Better and Stay Motivated
Arpit Mohan
0
 minutes ↗
#
career
#
beginners
#
productivity
Engineering

Recently I met my college friend Aditya Rao. I've known him for more than a decade and always thought of him as a business & marketing leader. I was surprised to hear that he's been learning programming for more than 2 years now. I got curious to know about his experience of learning to code and we ended up chatting for about 2 hours about his journey as a 30-year-old beginner developer.

Here are a few tips he shared that helped him learn better and stay motivated through the course. I think other beginners will find these tips useful too, so I am sharing them here.

These are Aditya’s words, slightly edited by me for better readability.

1. Get rid of self-imposed starting barriers I took two computer programming courses during my undergraduate and I failed both. For a really long time, I thought that programming is some black box that's too complex & hard. This skewed view created a starting barrier for me. I know many people who are completely new to programming feeling the same way.

After 3 years, I can say that programming is anything but a black box. It is just beautiful. Something as simple as CSS is truly magical. Everyone has different mental barriers and most of those are self-created. Don’t get intimidated by these self-imposed views.

2. Be clear about your end goal When I was just starting out, an engineer friend told me, "When programmers can’t understand an error message in their code, they go and search the internet to figure out what that error is. There are probably other engineers out there who have faced and solved the same problem before. So, they take that solution and try it out. Of course, they have their fundamentals in place but everyone is still learning on the go.”

Learning on the go made sense to me. Moreover, it was quite liberating to hear this. I took this approach to learning & told myself - ‘I am not here to learn coding, I am here to solve a problem’. This approach of focusing on solving the problem at hand has empowered me to learn faster & better.

3. “You can get anywhere if you simply go one step at a time.” Pick up a small problem. Take out one weekend and just start solving it. The key is to get a small win and then to keep stacking up these small successes. The best thing about code is that it is repeatable. If you have a small piece of code that solves a small problem, you can always extend that to solve a larger problem later on.

Engineers take a big problem and break it down into smaller & simpler steps quite beautifully. If the small solutions for each step work, they can be put together to achieve a larger goal. This is the most valuable life skill I have learned while learning to code.

4. Ask for help & unblock yourself ASAP Coding isn’t hard by itself unless you are building a really breakthrough technology or the world’s next best search engine. But there are hard parts such as setting up AWS and setting up other infrastructure as needed. You will need a lot of help with these things. Always be ready to seek help.

When I asked my first question on StackOverflow, I got 5 downvotes on it. I was genuinely trying to understand something and people were telling me that I am not asking the question in the right way. It was demotivating for me as a beginner. Even if such things happen a couple of times, don't let random people deter you in asking for help from experienced engineers. The Internet, my engineering friends, and colleagues have helped me learn the most.

5. Build something useful to stay motivated I am a big proponent of the no-code movement. Technology should be like a bunch of Lego blocks anyone can play around with. Kids don't think how a lego block gets made, what is the material used or what its tensile strength is. They just use it to build something they want. I am sure there are people out there who care about the perfect piece of code. I have no benchmark on what is good code or bad code. The only benchmark I have is to build something that people find useful. I feel successful when I build something and people value it.

Checkout Aditya’s latest side project, TimeSpent.

Is it Worth Joining an Early-stage Startup?
31
July
2019
Engineering

Is it Worth Joining an Early-stage Startup?

Is it Worth Joining an Early-stage Startup?
Arpit Mohan
0
 minutes ↗
#
startup
#
hiring
#
career
#
beginners
Engineering

This post is an attempt to put some method to the madness behind deciding whether joining an early-stage startup is worth it.

"The short answer is that it depends."

For the long answer — I have a framework to share that has helped me decide this multiple times in the past. Over the last 10 years, I have co-founded two startups, Gharpay & Bicycle AI, and worked at a few early-stage startups such as Exotel and Cure.Fit. About a month ago, I started building my third startup, Appsmith.

The challenge of working on new problems for new markets is a heady combination for me. But each time I started up or joined an early-stage startup, I found myself asking, “Is it worth it?” Though my answer has always been a resounding “yes”, my reasons behind the “yes” were different each time. I found that clarity on my reason behind the decision was critical.

We all have different life contexts, priorities, personalities and dreams. These unique factors influence our reasoning for choosing one career path over another. You shouldn’t let anyone tell you to ignore this stuff and just jump in.

So, here is my framework. It is quite simple and focuses on a few fundamentals.

Step 1: Ask three questions about yourself and answer honestly.

Step 2: Explore three reasons why it may be a bad idea to join an early-stage startup.

Step 3: Explore three reasons why it may be a fantastic idea to join an early-stage startup.

Step 1: The Three Critical Questions**

1. What kind of life do you want — right now and in the long term?

The answer depends heavily on your personal and professional goals. What are your priorities? Are you willing to invest a considerable amount of mental energy & time in your professional life right now? How does working at an early-stage startup fit within those priorities? Does it help or hamper your progress towards your long-term goals?

Personally, If I have a lot going on my personal front, I will want to prioritize that and hold out on making major commitments on my professional front. Try getting some clarity on what is your priority right now & what you want from life in the long-term. Clarity of thought acts as a great north star for all the decisions that you will end up taking.

2. What kind of a person are you?

Early-stage startups are not better or worse than late-stage startups or even large corporations. They are just different. And from what I have noticed, most people who fit in and perform well at early stages have a few overarching traits.

They are generalists. They look at their work as their craft and take great pride in it. They love challenges and are self-motivated to figure things out. They are quite comfortable saying ‘I don’t know’. They ask for help without hesitation. They also index heavily on finding a solution instead of focusing on the problem. Last but not the least, they are resilient.

Do parts of it seem like you? Look within and answer candidly.

3. What do you expect to gain from it?

Begin with the (expected) end in mind. What kind of professional growth do you need? What are your “must meet” and “good to meet” expectations from yourself at this point? Define these clearly. Take a step back and ask yourself — why are you even thinking of joining an early-stage startup in the first place?

If you don’t know what output you want, you can’t really decide what input to give and how to program the system, can you? State clearly what you want to gain from the experience.

Step 2: Why is joining an early stage startup a bad idea

1. Ambiguity gets a seat on the table

"No company (of any scale) has everything figured out."

The earlier a company is in its lifecycle, the more the number of unanswered questions. The work environment at early-stage startups can be a little (or very) chaotic because of this inevitable ambiguity.

You will not face much ambiguity on a daily basis at a late-stage startup or bigger company because they have already gone through their ambiguous phase. Whatever ambiguities are left to be figured out exist at the management level while you are shielded from it.

Everyone at an early-stage startup must embrace ambiguity. If you are not okay working with some level of uncertainty & ambiguity, early-stage startups may not be a good choice for you.

2. Get it right and get it fast, please.

"You can have something good or you can have something right now but you can’t have something good right now."

Early-stage startups don’t subscribe to this thought process. You got to deliver on everything super fast. You got to think fast, plan fast, build fast, ship fast and iterate fast. The company’s survival & success depends on how quickly it can execute & iterate on multiple things simultaneously. Some people choose to accomplish this by working longer hours, while others choose to do it by creating leverage (a topic for another day).

Timelines are mostly tight. You’ve got to deliver things right and you’ve got to deliver them fast. If you don’t subscribe to this work-style or if you feel this may stress you out, early-stage startups may not be a good professional choice.

3. ROI is subject to market risk and yes, it takes a long time to get any returns

The answer to ‘will your investment reap financial returns’ is always a probabilistic one. Same is the case with startups. Reaping any sizeable financial returns on your equity or ESOP (Employee Stock Option Pool) takes quite a bit of time. Standard equity or ESOP vesting periods span over four years.

Yes, there is a potential of high returns (more on this later) but you must also consider any financial trade-offs you are making. And don’t ignore the time frame of any expected ROI. Most early-stage VCs invest with a 10-year horizon.

"A garden takes time to cultivate before you see the flowers bloom. Early-stage startups are definitely not get-rich-quick schemes. "

If you need to make a lot of money quickly, early-stage startups are not your best bet.

Step 3 : Why is joining an early-stage startup a fantastic idea

1. A free ‘personal growth 101’ class

There is a lot to be done and everyone has limited bandwidth. You are mostly on your own. You will need to figure out how to do things yourself. How do you make technical choices? How do you sell the product to a potential customer? How do you pitch the team and its culture to a potential candidate? How do you say no? How do you prioritize for maximum output & outcomes?

There are no manuals to refer or company best practices to follow at early-stage startups. You’ve got to write these yourself. The learning curve is really steep when you get down to laying the foundation. Once you do these things from scratch, you’ll realize that you can figure out most things in life. You don’t have to rely on external folks/factors to accelerate learning. This builds a lot of self-confidence.

"Startups test your character and your core beliefs. "

How do you react when you are under pressure? What choices do you make when nobody is watching? How do you handle rejection from investors and customers? Are you able to take critical feedback and improve? You will uncover a lot about yourself while navigating such choices.

2. Diverse exposure

Are you an engineer? Great! You also have to pitch and sell the product to early customers. Are you a sales ninja? Cool! Please pitch in for writing the social media posts too. You do marketing? Awesome! Can you get on some customer feedback calls as well?

Sure, late-stage startups and large enterprises allow you to develop vertical depth of subject matter. But early-stage startups equip you with practical knowledge of how different verticals work and how they interact with each other to form a well-functioning organisation.

Early-stage startups push you to get out of your comfort zone regularly by exploring things out of your domain.

This experience will equip you with a lot more tools in your professional kitty. This diverse exposure is really useful in the job market of today and of the future.

3. Low risk, high reward investment (equity/ESOP)

I understand the value of equity wealth. In fact, one of the main reasons that I quit my day job to startup was to generate equity wealth.

Typically, early team members at startups get 0.2% — 2% equity share (depending on your experience, contribution, stage of the company etc). Early equity is given for risk rather than contribution. That’s why a founder’s equity is much higher than that of early team members.

Let’s run the numbers and see how early equity pans out in three scenarios. The assumption here is that you work at a fictitious startup that’s paying you a salary of 100K USD per year along with a total of 100K USD stock options (vested over 4 years).

Scenario 1:

equity-1.png

Assuming the startup is growing at 2x in valuation for the first couple of years, your equity will be worth 1.6 million USD. In contrast, you’d only make 400K USD as salary over the 4 years.

Scenario 2:

Assuming the valuation grows at the rate of 2x for the first two years; post which, it grows at 1.5x each year. In this case, your equity will be worth 900 K USD.

equity-2.png

Scenario 3:

Let’s take an even more conservative approach and assume that the valuation only increases 1.5x each year for the entire 4 years duration of your vesting period. Even in this case, your equity will be worth 506,250 USD.

equity-3.png

While the gap between equity wealth and salary wealth has narrowed down significantly from scenario 1 to scenario 3, equity wealth is still higher than the overall salary for a startup walking a conservative growth path. Of course, the equity wealth can reduce to zero too if the startup shuts down or the valuations take a downward spiral.

Since most startups pay competitive salaries, ESOPs give you an extreme financial upside while limiting the downside. This ensures you can pay your mortgage, send your kids to school and also save for the future.

In light of the context above, you should have more clarity on whether the decision to join an early-stage startup is worth it for you.

I hope this helps you in reaching your decision. Happy to answer any other questions that you may have around early-stage startups. You can reach me at arpit@appsmith.com

P.S — In case you decide that you want to join an early-stage startup, we are hiring for engineering roles. Hit me up and let’s chat.