29
April
2021
Resources

Building an Admin Dashboard with React-admin

React admin has been one of the holy grail frontend frameworks for building responsive admin panels. It offers a lot of really cool features such as data validation, optimistic rendering, accessibility, and action undo. React-admin is also plug-and-play as it supports standard REST APIs and a handful of GraphQL dialects. Being a Reactjs framework, it also gives you access to thousands of plugins and libraries available in Javascript and the React ecosystem.

In this article, I would like to show you how to build an admin panel using React-admin.

We’re going to be building a dashboard to manage DVD movie rentals for a local rental store. The first page would have a table listing all registered members of the store. The second page will have a table that holds all rental records. From here, new rental entries can be created and existing rentals can be updated i.e from borrowed to returned. We would also be able to click on a customer from the first page and then be taken to the rentals page to see his rental history.

Here’s a gif and a link to the completed application

You can view the demo app here

Dashboard link: as-react-admin.netlify.app

username: cokoghenun@appsmith.com

password: 123456

Through building this dashboard, we’re going to cover core React-admin concepts such as

  • Resources
  • List view
  • Edit/Create view
  • Reference inputs and
  • Authentication

Since React-admin requires an API server we would need to build one on top of the database. Speaking of the database, we’ll be making use of MongoDB and the demo dataset is a modified version of the Sakila dataset.

To save time and get to the fun part of building the dashboard with React-admin, we’ll be making use of Loopback to generate a Nodejs API over the database. If you are not familiar with Loopback, it is a highly extensible Node.js and TypeScript framework for building APIs and microservices.

You can skip this if you already have an API to use

We’re almost set. But before we begin, I’d like to give you a mini-map of the entire article. The first part of this article will focus on generating an API server over the database on MongoDB using Loopback. The second part of this article would cover how to use React-admin to build a dashboard from the API generated in the first section.

Alright, everything looks good. Let’s get started!

Generating an API server

There are many ways to build an API server. You can roll up your sleeves and build one yourself(this takes a lot of time) or you can choose to go with a framework. Loopback is the fastest framework I found to build Nodejs APIs over a database. It supports a host of databases ranging from in-memory to document to relational databases.

The API that would be generated using Loopback will have three resources, the first being the customer resource that represents customers who come to rent DVDs from the store. We also have the film resource, representing DVDs that are in stock. Lastly, we have the rentals resource, which records each rental.

Here’s the schema for each resource

// Customer resource{
  "store_id": String,
  "first_name": String,
  "last_name": String,
  "email": String,
  "address_id": String,
  "activebool": Boolean,
  "create_date": Date,
  "last_update": Date,
  "active": Number
}


// Film resource
{
  "title": String,
  "description": String,
  "release_year": Number,
  "language_id": String,
  "rental_duration": Number,
  "rental_rate": Number,
  "length": Number,
  "replacement_cost": Number,
  "rating": String,
  "last_update": Date,
  "special_features": String,
  "fulltext": String
}

// Rental resource
{
  "status": String,
  "rental_date": Date,
  "film_title": String,
  "customer_email": String,
  "return_date": Date,
  "staff_id": String,
  "last_update": Date
}

Okay! Now let’s get started by install Loopback CLI with npm

npm i -g @loopback/cli

We can easily scaffold the Nodejs server using the Loopback CLI. It configures a Typescript compiler and installs all required dependencies. Let’s run the CLI and answer a few prompts to generate a new app

lb4 app

You should have your app configured as shown below

Hit enter and give the CLI some time to set up the app.

Creating a model

Now that the loopback app has been scaffolded, cd (change directory) into the app folder, and let’s start by creating a model for each resource. A model communicates the shape of each document for a particular resource, much like the schema shown earlier.

Let’s create a model for the customer resource using the Loopback CLI

lb4 model

As we did when generating the app, answer the CLI prompts. Yours should look like this

3-configuring the customer model.png

Great Job! Now, go ahead and do the same for the film and rental resources. Don’t forget that to create a new model, you’ll need to run the lb4 model command.

Connecting to the database

Next, we’ll need to link the Loopback app to the Mongo database. Loopback provides two entities to help us accomplish this, and they are the datasource and repository mechanisms.

A datasource represents a database connection that would be used to store and retrieve documents from the database i.e MongoDB or PostgreSQL. On the other hand, a repository links a resource on the Loopback app to a particular table or collection in the database. For example, the customer resource is linked to the Customer collection in the database using a repository.

Now, let’s add a datasource to the app, and link it to our MongoDB database. We can easily do this using the CLI command below

lb4 datasource

As usual, go ahead and answer the CLI prompts, supplying the database credentials to the CLI

4-configuring the mongo datasource.png

Awesome! Now we can add a repository for each resource.

Run the command below and let’s set up a repository for the customer resource. Notice that we have to link the created resource to the target resource, and in this case, it is the customer resource

lb4 repository

Cool! Go ahead and do the same for the film and rental repositories. I’m confident you can finish up on your own 😜

Adding CRUD functionality

Great Job! That was a lot we just covered. Right now, we have models for each resource, a datasource, and repositories linking each model to its respective collection in the database.

The last piece of the puzzle is to add CRUD functionality for each resource.

We can do this by creating controllers. Controllers do the grunt work of creating, reading, updating, and deleting documents for each resource.

As you may have already guessed, we can create a controller using the controller command. Now, let’s create a REST controller for the customer resource. Notice we’ll need to use the model and repository created earlier for the customer resource.

lb4 controller
Note that the Id is a string and is not required when creating a new instance
6-creating a controller.png

As usual, go ahead and do the same for the film and rental resources.

Awesome! We now have a full-blown REST API that was generated in a few minutes. Open up the project folder in your favorite code editor and you’ll see all the code(and folders) generated by Loopback.

I recommend you change the default port in the index.ts file to something else i.e 4000 because Create React App (used by React-admin) runs by default on port 3000

You can start the server using the start script

npm start

You can find a playground and the auto-generated API documentation for your server by visiting the server address on your browser i.e http://localhost:4000/

7-api explorer.png

Alright! Now we have a REST API server with CRUD functionality, we can move on with creating the admin dashboard for using React-admin.

Enter React-admin

We’ve finally gotten to the fun part, yay!

As a quick recap, we have a Loopback API generated in the last section that serves the customer, film, and rental resource with the following endpoints and data schema

// /customers endpoint
{
  "store_id": String,
  "first_name": String,
  "last_name": String,
  "email": String,
  "address_id": String,
  "activebool": Boolean,
  "create_date": Date,
  "last_update": Date,
  "active": Number
}


// /films endpoint
{
  "title": String,
  "description": String,
  "release_year": Number,
  "language_id": String,
  "rental_duration": Number,
  "rental_rate": Number,
  "length": Number,
  "replacement_cost": Number,
  "rating": String,
  "last_update": Date,
  "special_features": String,
  "fulltext": String
}

// /rentals endpoint
{
  "status": String,
  "rental_date": Date,
  "film_title": String,
  "customer_email": String,
  "return_date": Date,
  "staff_id": String,
  "last_update": Date
}

So here’s the game plan. We’re going to use this API to build a dashboard to manage DVD movie rentals. The first page would be a table showing all customers. Then we can click on a customer and view all his rentals on a new page. We can update the return date and status of each rental i.e from borrowed to returned. Lastly, we can view all rentals on the rentals page and create a new entry or edit an existing one.

Phew! Now we can finally begin with React-admin 😅

React-admin is a powerful front-end framework for building admin panels and dashboards. It is highly customizable and has a host of other great features. Since it is based on Reactjs, it can be used with thousands of other Reactjs and Javascript libraries.

React admin requires a base Reactjs project. We are going to be going with Create-React-App (CRA) in this article. So let’s set up the project with CRA

npx create-react-app rental-admin-panel

Give the CLI some time to install all dependencies and finish setting up the project. Then, cd into the project directory and go-ahead to install React-admin and the Loopback dataprovider.

npm install react-admin react-admin-lb4

A dataProvider is the mechanism with which React-admin communicates with a REST/GraphQL API. The Loopback provider for React-admin enables it to understand and use Loopback APIs i.e how to paginate or filter requests. If you aren’t using a Loopback generated API, you should look into using one of these dataProviders for React-admin.

Open up the project in your favourite code editor and replace everything in the App.js file with the below starter code

//src/App.js

import React from 'react';
import lb4Provider from 'react-admin-lb4';
import { Admin, Resource } from 'react-admin';

function App() {
  return (
    // ------------- Replace the below endpoint with your API endpoint -------------
    
      
    
  );
}

export default App;

So far so good. But we have some new concepts to clear up. In the starter code above, we supply a dataProvider to React-admin which enables it to query the API. The next thing we did up there is to register a resource from the API that we would like to use in React-admin. This is done simply by supplying the endpoint as a name prop to the <Resource> component.

You don’t need to add the forward-slash “/” to the resource name

Going by this rule, we must register it as a resource whenever we need to query a new API endpoint. In this way, React-admin becomes aware of it. Moving on...

Creating the Customers' table

The easiest way to view all customers’ info is to have a paginated table displaying all customers’ info. React-admin makes it easy to do this by providing us with a <List> component.

The <List> component generates a paginated table that lists out all documents in a particular resource. We can choose which fields we want to show up on the table by wrapping them in the appropriate <Field> component i.e a date property on a document would be wrapped in a <DateField> component.

The data property on the document is linked to the <Field> component using the source prop. This prop must contain the exact property name. And the field name showing up on the table can be customized using the label prop.

We can also create a filter for the table using the <Filter> component and specify an action to be triggered whenever an item is clicked on the table using the rowClick props on the <Datagrid> component. You can learn more about filtering here and row actions here

Alright! So we want a customer table to show all the customers. We also want this table to be filterable by customer email. Lastly, we want to be able to click on a customer and see all his rentals (we haven’t created the rentals page yet, but we will shortly).

Let’s see all of this in action. Go ahead to create a customer list component with the following content

//src/components/CustomerList.js

import React from 'react';
import { List, Filter, Datagrid, TextField, SearchInput, } from 'react-admin';

// ------------- filter component which filters by customer email -------------
const CustomerFilter = (props) => (
  
    
  
);

const CustomerList = (props) => (
  } title='List of Customers'>
// ------------- rowclick action that redirects to the rentals of the selected customer using the customer id -------------
     {
        return `/rentals?filter=%7B%22customer_email%22%3A%22${record.email}%22%7D&order=ASC&page=1&perPage=10&sort=film_title`;
      }}
    >
      
      
      
      
      
    
  
);

export default CustomerList;

Next, we need to link the <CustomerList> component with the customer resource component.

//src/App.js

// ------------- import CustomerList -------------
import CustomerList from './components/CustomerList'; 

//…

// ------------- use CustomerList as the list view on the customer resource -------------

Save your code and let’s head over to the browser. You can see we have a nice paginated, and filterable customer table that has been automatically generated and is rendering customer information from the API. Cool right? 😎

8-customer table ui.png

Not so fast! Go ahead and create a similar list table for the rental resource. You can name this component RentalList. If you are curious or get stock, feel free to fall back on the code here.

Creating and Editing a Rental

We have two more views to create and they are the edit and create view for the rental resource. They are quite similar to each other and are both similar to the list view but with a few differences.

The edit view would be used to edit an item clicked on the rental table.

To wire up this behaviour ensure that you have rowClick='edit' on the <Datagrid> component in <RentalList>

An edit view uses a <SimpleForm> component, which in reality is a simple form with nested <Input> components. Like with the <Field> components, each <Input> component used is based on the data type of the property to be edited i.e a <TextInput> component is used on a text property. Inputs also require the source props and optional label props as we’ve already seen with the <Field> component.

Bringing it all together, the edit view for the rental resource would look like this:

Notice that some inputs have been disabled using the disabled props
// src/components/RentalEdit.sj
import React from 'react';
import {
  Edit,
  SimpleForm,
  TextInput,
  DateTimeInput,
  SelectInput,
} from 'react-admin';

const RentalEdit = (props) => (
  
    
      
      
      
      

      
      
    
  
);

export default RentalEdit;

Don’t forget to import and use the edit view in the rental resource component in your App.js file.


//src/App.js

// ------------- import RentalEdit' -------------
import RentalEdit from './components/RentalEdit'; 

//…

// ------------- use RentalEdit as the edit view on the rental resource -------------
 

Save your files and let’s head to the browser. Click on an order to see the magic!

Okay, so we’ve completed the edit view. Now moving on to make the create view.

The create view is quite similar to the edit view. It’s so similar that I’m just going to paste the code right here and you wouldn’t be able to tell the difference. Just kidding 😜. Anyway, here’s the code for the create view

// src/components/RentalCreate.js
import React, { useState, useEffect } from 'react';
import {
  Create,
  SimpleForm,
  DateTimeInput,
  SelectInput,
  useNotify,
  useRefresh,
  useRedirect,
  useQuery,
  TextInput,
} from 'react-admin';

const RentalCreate = (props) => {
  const notify = useNotify();
  const refresh = useRefresh();
  const redirect = useRedirect();

  const onSuccess = ({ data }) => {
    notify(`New Rental created `);
    redirect(`/rentals?filter=%7B"id"%3A"${data.id}"%7D`);
    refresh();
  };

  const [customers, setCustomers] = useState([]);
  const { data: customer } = useQuery({
    type: 'getList',
    resource: 'customers',
    payload: {
      pagination: { page: 1, perPage: 600 },
      sort: { field: 'email', order: 'ASC' },
      filter: {},
    },
  });

  const [films, setFilms] = useState([]);
  const { data: film } = useQuery({
    type: 'getList',
    resource: 'films',
    payload: {
      pagination: { page: 1, perPage: 1000 },
      sort: { field: 'title', order: 'ASC' },
      filter: {},
    },
  });


  useEffect(() => {
    if (film) setFilms(film.map((d) => ({ id: d.title, name: d.title })));
    if (customer)
      setCustomers(customer.map((d) => ({ id: d.email, name: d.email })));
  }, [film, customer]);

  return (
    
      
        
        
        
        

        

        
      
    
  );
};

export default RentalCreate;

The only difference here is that we have two select inputs that display a list of all customers and films by manually querying those resources.

Instead of writing custom logic to query the customer and film resources, we could have easily use the built-in <ReferenceInput> component. But currently, there's no way to set the selected value from the <SelectInput> component to something other than the document id. In the create form, we require the email field from the customer resource and the title field from the film resource. That is why we are manually querying, else the <ReferenceInput> component would have been awesome.

Do not forget to import and use the create view we just made. Also, register the film resource in App.js

//src/App.js

// ------------- import RentalCreate -------------
import RentalCreate from './components/RentalCreate';


//…

// ------------- use RentalCreate as the create view on the rental resource -------------
 
// ------------- register the film resource -------------
 
If a resource is registered and no list view is passed to it, React-admin hides it from the navbar. But the resource is still useful for querying as we did for the film select input in the <RentalCreate> component.

This is the moment you’ve been waiting for! Save your files and head over to the browser. You’ll notice that we now have a create button on the rentals table, and clicking on a rental takes you to edit that rental. Sweet!

We’ve finally completed the dashboard! 🥳 🎉 🎊

We have a complete admin panel to manage rentals. We can see a list of customers, select a customer and view all his orders and lastly, we can create new rental entries or edit existing ones. Awesome!

For some extra credit, let's add some authentication.

Extra credit: Authentication

You must add some authentication to your apps, else anyone would be able to use it, even malicious individuals! Thankfully, adding authentication to our API and admin dashboard is not too difficult.

The first part of this section will focus on adding authentication to the Loopback API. You can skip this if you’ve been following along with your API. Next, we’ll look at implementing auth on the React-admin panel.

Securing the API

Loopback has various authentication strategies that we can implore to secure the API. We are going to be going with the JWT authentication strategy, mostly because it’s super easy to set up and is fully supported by React-admin.

Enough talk, let's get started by installing the JWT auth extension library and Validatorjs on the Loopback API server.

npm i --save @loopback/authentication @loopback/authentication-jwt @types/validator

Next, bind the authentication components to the application class in src/application.ts

// src/appliation.ts

// ----------- Add imports -------------
import {AuthenticationComponent} from '@loopback/authentication';
import {
  JWTAuthenticationComponent,
  SECURITY_SCHEME_SPEC,
  UserServiceBindings,
} from '@loopback/authentication-jwt';
import {MongoDataSource} from './datasources';
// ------------------------------------

export class TodoListApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {

    //…

    // ------ Add snippet at the bottom ---------

    // Mount authentication system
    this.component(AuthenticationComponent);
    // Mount jwt component
    this.component(JWTAuthenticationComponent);
    // Bind datasource
    this.dataSource(MongoDataSource, UserServiceBindings.DATASOURCE_NAME);
    // ------------- End of snippet -------------
  }
}

Great job! We now have a foundation for auth.

Authentication usually works by validating the credentials of the user attempting to sign in and allowing him to go through if valid credentials are supplied. Thus, we’ll then need to create a user resource to represent a user. For our purposes, a user only has an id and an email field.

Alright, let’s create the user model using the Loopback CLI. Answer the CLI prompts as usual

lb4 model

11-user model.png

We’ll also need to create a controller for the user resource that handles all authentication logic. You can use the CLI to generate an empty controller.

Note that this controller would need to be an empty controller and not a REST controller
lb4 controller
12-user controller.png

The generated empty controller file can be found in src/controllers/user.controller.ts. Copy the contents of the file linked here into your controller file. It contains all the authentication logic. You can find the file here

Visit the link above and copy its contents into the user.controller.ts file

Finally, we can secure the customer resource by adding the authentication strategy we just implemented to its controller. Here’s how to do it:

// src/controllers/order.controller.ts

// ---------- Add imports -------------
import {authenticate} from '@loopback/authentication';

// ------------------ Add auth decorator -----------
@authenticate('jwt') // <---- Apply the @authenticate decorator at the class level
export class CustomerController {
  //...
}

Do the same for the film and rental resources by adding the authentication strategy to their respective controller files.

And that’s it! Visiting the API playground on the browser http://localhost:4000/explorer/ you’ll notice we have a nice green Authorize button at the top of the page. We also now have signup and login routes to create user accounts and log in.

You’ll need to use this playground/explorer to create a new user

Now, let’s use this authentication on the React-admin dashboard.

Adding authentication to React-admin

Implementing authentication on the React-admin dashboard is fairly straightforward. We need an authProvider which is an object that contains methods for the authentication logic, and also a httpClient that adds the authorization header to every request made by the dashboard.

Create an Auth.js file in src/Auth.js that contains the authProvider method, and the httpClient function. Here’s what the content of the file should be

// src/Auth.js

export const httpClient = () => {
  const { token } = JSON.parse(localStorage.getItem('auth')) || {};
  return { Authorization: `Bearer ${token}` };
};

export const authProvider = {
  // authentication
  login: ({ username, password }) => {
    const request = new Request(
      process.env.REACT_APP_API_URL + '/users/login',
      {
        method: 'POST',
        body: JSON.stringify({ email: username, password }),
        headers: new Headers({ 'Content-Type': 'application/json' }),
      }
    );
    return fetch(request)
      .then((response) => {
        if (response.status < 200 || response.status >= 300) {
          throw new Error(response.statusText);
        }
        return response.json();
      })
      .then((auth) => {
        localStorage.setItem(
          'auth',
          JSON.stringify({ ...auth, fullName: username })
        );
      })
      .catch(() => {
        throw new Error('Network error');
      });
  },
  checkError: (error) => {
    const status = error.status;
    if (status === 401 || status === 403) {
      localStorage.removeItem('auth');
      return Promise.reject();
    }
    // other error code (404, 500, etc): no need to log out
    return Promise.resolve();
  },
  checkAuth: () =>
    localStorage.getItem('auth')
      ? Promise.resolve()
      : Promise.reject({ message: 'login required' }),
  logout: () => {
    localStorage.removeItem('auth');
    return Promise.resolve();
  },
  getIdentity: () => {
    try {
      const { id, fullName, avatar } = JSON.parse(localStorage.getItem('auth'));
      return Promise.resolve({ id, fullName, avatar });
    } catch (error) {
      return Promise.reject(error);
    }
  },
  getPermissions: (params) => Promise.resolve(),
};

Alright! Now let’s make use of the authProvider and httpClient in our app. Import authProvider and httpClient from ‘Auth.jsintoApp.jsand passhttpClientas a second parameter tolb4Provider. Then add an authProvider prop to theAdmincomponent and pass inauthProvider` as its value.

Simple and easy!

// ----------- Import Auth -------------
import { authProvider, httpClient } from './Auth';

//…

// ------------ Use httpClient and authProvider in the Admin component ---------
 //...

Save the files and head back to the browser and you’ll be greeted with a login screen. Fill in the email and password of your registered user and you’ll be taken to the customers’ table like before.

And that’s it! We now have a super-secured app! 💪

Deploy 🚀

We now have a fully functional admin dashboard with authentication. Lastly, I’ll like to walk you through deployment to your favourite cloud provider.

Since the API generated using Loopback is a standard Nodejs server, you can deploy your app to any Nodejs hosting provider i.e Heroku or Glitch. But note that you will need to move all packages under devDependencies to the dependencies section in your package.json file.

And for the React-admin dashboard, you can deploy it on any static hosting service i.e Netlify or Vercel. Don’t forget to replace the lb4Provider URL with that of your hosted backend.

Building an Admin Dashboard with React-admin

Share this

React admin has been one of the holy grail frontend frameworks for building responsive admin panels. It offers a lot of really cool features such as data validation, optimistic rendering, accessibility, and action undo. React-admin is also plug-and-play as it supports standard REST APIs and a handful of GraphQL dialects. Being a Reactjs framework, it also gives you access to thousands of plugins and libraries available in Javascript and the React ecosystem.

In this article, I would like to show you how to build an admin panel using React-admin.

We’re going to be building a dashboard to manage DVD movie rentals for a local rental store. The first page would have a table listing all registered members of the store. The second page will have a table that holds all rental records. From here, new rental entries can be created and existing rentals can be updated i.e from borrowed to returned. We would also be able to click on a customer from the first page and then be taken to the rentals page to see his rental history.

Here’s a gif and a link to the completed application

You can view the demo app here

Dashboard link: as-react-admin.netlify.app

username: cokoghenun@appsmith.com

password: 123456

Through building this dashboard, we’re going to cover core React-admin concepts such as

  • Resources
  • List view
  • Edit/Create view
  • Reference inputs and
  • Authentication

Since React-admin requires an API server we would need to build one on top of the database. Speaking of the database, we’ll be making use of MongoDB and the demo dataset is a modified version of the Sakila dataset.

To save time and get to the fun part of building the dashboard with React-admin, we’ll be making use of Loopback to generate a Nodejs API over the database. If you are not familiar with Loopback, it is a highly extensible Node.js and TypeScript framework for building APIs and microservices.

You can skip this if you already have an API to use

We’re almost set. But before we begin, I’d like to give you a mini-map of the entire article. The first part of this article will focus on generating an API server over the database on MongoDB using Loopback. The second part of this article would cover how to use React-admin to build a dashboard from the API generated in the first section.

Alright, everything looks good. Let’s get started!

Generating an API server

There are many ways to build an API server. You can roll up your sleeves and build one yourself(this takes a lot of time) or you can choose to go with a framework. Loopback is the fastest framework I found to build Nodejs APIs over a database. It supports a host of databases ranging from in-memory to document to relational databases.

The API that would be generated using Loopback will have three resources, the first being the customer resource that represents customers who come to rent DVDs from the store. We also have the film resource, representing DVDs that are in stock. Lastly, we have the rentals resource, which records each rental.

Here’s the schema for each resource

// Customer resource{
  "store_id": String,
  "first_name": String,
  "last_name": String,
  "email": String,
  "address_id": String,
  "activebool": Boolean,
  "create_date": Date,
  "last_update": Date,
  "active": Number
}


// Film resource
{
  "title": String,
  "description": String,
  "release_year": Number,
  "language_id": String,
  "rental_duration": Number,
  "rental_rate": Number,
  "length": Number,
  "replacement_cost": Number,
  "rating": String,
  "last_update": Date,
  "special_features": String,
  "fulltext": String
}

// Rental resource
{
  "status": String,
  "rental_date": Date,
  "film_title": String,
  "customer_email": String,
  "return_date": Date,
  "staff_id": String,
  "last_update": Date
}

Okay! Now let’s get started by install Loopback CLI with npm

npm i -g @loopback/cli

We can easily scaffold the Nodejs server using the Loopback CLI. It configures a Typescript compiler and installs all required dependencies. Let’s run the CLI and answer a few prompts to generate a new app

lb4 app

You should have your app configured as shown below

Hit enter and give the CLI some time to set up the app.

Creating a model

Now that the loopback app has been scaffolded, cd (change directory) into the app folder, and let’s start by creating a model for each resource. A model communicates the shape of each document for a particular resource, much like the schema shown earlier.

Let’s create a model for the customer resource using the Loopback CLI

lb4 model

As we did when generating the app, answer the CLI prompts. Yours should look like this

3-configuring the customer model.png

Great Job! Now, go ahead and do the same for the film and rental resources. Don’t forget that to create a new model, you’ll need to run the lb4 model command.

Connecting to the database

Next, we’ll need to link the Loopback app to the Mongo database. Loopback provides two entities to help us accomplish this, and they are the datasource and repository mechanisms.

A datasource represents a database connection that would be used to store and retrieve documents from the database i.e MongoDB or PostgreSQL. On the other hand, a repository links a resource on the Loopback app to a particular table or collection in the database. For example, the customer resource is linked to the Customer collection in the database using a repository.

Now, let’s add a datasource to the app, and link it to our MongoDB database. We can easily do this using the CLI command below

lb4 datasource

As usual, go ahead and answer the CLI prompts, supplying the database credentials to the CLI

4-configuring the mongo datasource.png

Awesome! Now we can add a repository for each resource.

Run the command below and let’s set up a repository for the customer resource. Notice that we have to link the created resource to the target resource, and in this case, it is the customer resource

lb4 repository

Cool! Go ahead and do the same for the film and rental repositories. I’m confident you can finish up on your own 😜

Adding CRUD functionality

Great Job! That was a lot we just covered. Right now, we have models for each resource, a datasource, and repositories linking each model to its respective collection in the database.

The last piece of the puzzle is to add CRUD functionality for each resource.

We can do this by creating controllers. Controllers do the grunt work of creating, reading, updating, and deleting documents for each resource.

As you may have already guessed, we can create a controller using the controller command. Now, let’s create a REST controller for the customer resource. Notice we’ll need to use the model and repository created earlier for the customer resource.

lb4 controller
Note that the Id is a string and is not required when creating a new instance
6-creating a controller.png

As usual, go ahead and do the same for the film and rental resources.

Awesome! We now have a full-blown REST API that was generated in a few minutes. Open up the project folder in your favorite code editor and you’ll see all the code(and folders) generated by Loopback.

I recommend you change the default port in the index.ts file to something else i.e 4000 because Create React App (used by React-admin) runs by default on port 3000

You can start the server using the start script

npm start

You can find a playground and the auto-generated API documentation for your server by visiting the server address on your browser i.e http://localhost:4000/

7-api explorer.png

Alright! Now we have a REST API server with CRUD functionality, we can move on with creating the admin dashboard for using React-admin.

Enter React-admin

We’ve finally gotten to the fun part, yay!

As a quick recap, we have a Loopback API generated in the last section that serves the customer, film, and rental resource with the following endpoints and data schema

// /customers endpoint
{
  "store_id": String,
  "first_name": String,
  "last_name": String,
  "email": String,
  "address_id": String,
  "activebool": Boolean,
  "create_date": Date,
  "last_update": Date,
  "active": Number
}


// /films endpoint
{
  "title": String,
  "description": String,
  "release_year": Number,
  "language_id": String,
  "rental_duration": Number,
  "rental_rate": Number,
  "length": Number,
  "replacement_cost": Number,
  "rating": String,
  "last_update": Date,
  "special_features": String,
  "fulltext": String
}

// /rentals endpoint
{
  "status": String,
  "rental_date": Date,
  "film_title": String,
  "customer_email": String,
  "return_date": Date,
  "staff_id": String,
  "last_update": Date
}

So here’s the game plan. We’re going to use this API to build a dashboard to manage DVD movie rentals. The first page would be a table showing all customers. Then we can click on a customer and view all his rentals on a new page. We can update the return date and status of each rental i.e from borrowed to returned. Lastly, we can view all rentals on the rentals page and create a new entry or edit an existing one.

Phew! Now we can finally begin with React-admin 😅

React-admin is a powerful front-end framework for building admin panels and dashboards. It is highly customizable and has a host of other great features. Since it is based on Reactjs, it can be used with thousands of other Reactjs and Javascript libraries.

React admin requires a base Reactjs project. We are going to be going with Create-React-App (CRA) in this article. So let’s set up the project with CRA

npx create-react-app rental-admin-panel

Give the CLI some time to install all dependencies and finish setting up the project. Then, cd into the project directory and go-ahead to install React-admin and the Loopback dataprovider.

npm install react-admin react-admin-lb4

A dataProvider is the mechanism with which React-admin communicates with a REST/GraphQL API. The Loopback provider for React-admin enables it to understand and use Loopback APIs i.e how to paginate or filter requests. If you aren’t using a Loopback generated API, you should look into using one of these dataProviders for React-admin.

Open up the project in your favourite code editor and replace everything in the App.js file with the below starter code

//src/App.js

import React from 'react';
import lb4Provider from 'react-admin-lb4';
import { Admin, Resource } from 'react-admin';

function App() {
  return (
    // ------------- Replace the below endpoint with your API endpoint -------------
    
      
    
  );
}

export default App;

So far so good. But we have some new concepts to clear up. In the starter code above, we supply a dataProvider to React-admin which enables it to query the API. The next thing we did up there is to register a resource from the API that we would like to use in React-admin. This is done simply by supplying the endpoint as a name prop to the <Resource> component.

You don’t need to add the forward-slash “/” to the resource name

Going by this rule, we must register it as a resource whenever we need to query a new API endpoint. In this way, React-admin becomes aware of it. Moving on...

Creating the Customers' table

The easiest way to view all customers’ info is to have a paginated table displaying all customers’ info. React-admin makes it easy to do this by providing us with a <List> component.

The <List> component generates a paginated table that lists out all documents in a particular resource. We can choose which fields we want to show up on the table by wrapping them in the appropriate <Field> component i.e a date property on a document would be wrapped in a <DateField> component.

The data property on the document is linked to the <Field> component using the source prop. This prop must contain the exact property name. And the field name showing up on the table can be customized using the label prop.

We can also create a filter for the table using the <Filter> component and specify an action to be triggered whenever an item is clicked on the table using the rowClick props on the <Datagrid> component. You can learn more about filtering here and row actions here

Alright! So we want a customer table to show all the customers. We also want this table to be filterable by customer email. Lastly, we want to be able to click on a customer and see all his rentals (we haven’t created the rentals page yet, but we will shortly).

Let’s see all of this in action. Go ahead to create a customer list component with the following content

//src/components/CustomerList.js

import React from 'react';
import { List, Filter, Datagrid, TextField, SearchInput, } from 'react-admin';

// ------------- filter component which filters by customer email -------------
const CustomerFilter = (props) => (
  
    
  
);

const CustomerList = (props) => (
  } title='List of Customers'>
// ------------- rowclick action that redirects to the rentals of the selected customer using the customer id -------------
     {
        return `/rentals?filter=%7B%22customer_email%22%3A%22${record.email}%22%7D&order=ASC&page=1&perPage=10&sort=film_title`;
      }}
    >
      
      
      
      
      
    
  
);

export default CustomerList;

Next, we need to link the <CustomerList> component with the customer resource component.

//src/App.js

// ------------- import CustomerList -------------
import CustomerList from './components/CustomerList'; 

//…

// ------------- use CustomerList as the list view on the customer resource -------------

Save your code and let’s head over to the browser. You can see we have a nice paginated, and filterable customer table that has been automatically generated and is rendering customer information from the API. Cool right? 😎

8-customer table ui.png

Not so fast! Go ahead and create a similar list table for the rental resource. You can name this component RentalList. If you are curious or get stock, feel free to fall back on the code here.

Creating and Editing a Rental

We have two more views to create and they are the edit and create view for the rental resource. They are quite similar to each other and are both similar to the list view but with a few differences.

The edit view would be used to edit an item clicked on the rental table.

To wire up this behaviour ensure that you have rowClick='edit' on the <Datagrid> component in <RentalList>

An edit view uses a <SimpleForm> component, which in reality is a simple form with nested <Input> components. Like with the <Field> components, each <Input> component used is based on the data type of the property to be edited i.e a <TextInput> component is used on a text property. Inputs also require the source props and optional label props as we’ve already seen with the <Field> component.

Bringing it all together, the edit view for the rental resource would look like this:

Notice that some inputs have been disabled using the disabled props
// src/components/RentalEdit.sj
import React from 'react';
import {
  Edit,
  SimpleForm,
  TextInput,
  DateTimeInput,
  SelectInput,
} from 'react-admin';

const RentalEdit = (props) => (
  
    
      
      
      
      

      
      
    
  
);

export default RentalEdit;

Don’t forget to import and use the edit view in the rental resource component in your App.js file.


//src/App.js

// ------------- import RentalEdit' -------------
import RentalEdit from './components/RentalEdit'; 

//…

// ------------- use RentalEdit as the edit view on the rental resource -------------
 

Save your files and let’s head to the browser. Click on an order to see the magic!

Okay, so we’ve completed the edit view. Now moving on to make the create view.

The create view is quite similar to the edit view. It’s so similar that I’m just going to paste the code right here and you wouldn’t be able to tell the difference. Just kidding 😜. Anyway, here’s the code for the create view

// src/components/RentalCreate.js
import React, { useState, useEffect } from 'react';
import {
  Create,
  SimpleForm,
  DateTimeInput,
  SelectInput,
  useNotify,
  useRefresh,
  useRedirect,
  useQuery,
  TextInput,
} from 'react-admin';

const RentalCreate = (props) => {
  const notify = useNotify();
  const refresh = useRefresh();
  const redirect = useRedirect();

  const onSuccess = ({ data }) => {
    notify(`New Rental created `);
    redirect(`/rentals?filter=%7B"id"%3A"${data.id}"%7D`);
    refresh();
  };

  const [customers, setCustomers] = useState([]);
  const { data: customer } = useQuery({
    type: 'getList',
    resource: 'customers',
    payload: {
      pagination: { page: 1, perPage: 600 },
      sort: { field: 'email', order: 'ASC' },
      filter: {},
    },
  });

  const [films, setFilms] = useState([]);
  const { data: film } = useQuery({
    type: 'getList',
    resource: 'films',
    payload: {
      pagination: { page: 1, perPage: 1000 },
      sort: { field: 'title', order: 'ASC' },
      filter: {},
    },
  });


  useEffect(() => {
    if (film) setFilms(film.map((d) => ({ id: d.title, name: d.title })));
    if (customer)
      setCustomers(customer.map((d) => ({ id: d.email, name: d.email })));
  }, [film, customer]);

  return (
    
      
        
        
        
        

        

        
      
    
  );
};

export default RentalCreate;

The only difference here is that we have two select inputs that display a list of all customers and films by manually querying those resources.

Instead of writing custom logic to query the customer and film resources, we could have easily use the built-in <ReferenceInput> component. But currently, there's no way to set the selected value from the <SelectInput> component to something other than the document id. In the create form, we require the email field from the customer resource and the title field from the film resource. That is why we are manually querying, else the <ReferenceInput> component would have been awesome.

Do not forget to import and use the create view we just made. Also, register the film resource in App.js

//src/App.js

// ------------- import RentalCreate -------------
import RentalCreate from './components/RentalCreate';


//…

// ------------- use RentalCreate as the create view on the rental resource -------------
 
// ------------- register the film resource -------------
 
If a resource is registered and no list view is passed to it, React-admin hides it from the navbar. But the resource is still useful for querying as we did for the film select input in the <RentalCreate> component.

This is the moment you’ve been waiting for! Save your files and head over to the browser. You’ll notice that we now have a create button on the rentals table, and clicking on a rental takes you to edit that rental. Sweet!

We’ve finally completed the dashboard! 🥳 🎉 🎊

We have a complete admin panel to manage rentals. We can see a list of customers, select a customer and view all his orders and lastly, we can create new rental entries or edit existing ones. Awesome!

For some extra credit, let's add some authentication.

Extra credit: Authentication

You must add some authentication to your apps, else anyone would be able to use it, even malicious individuals! Thankfully, adding authentication to our API and admin dashboard is not too difficult.

The first part of this section will focus on adding authentication to the Loopback API. You can skip this if you’ve been following along with your API. Next, we’ll look at implementing auth on the React-admin panel.

Securing the API

Loopback has various authentication strategies that we can implore to secure the API. We are going to be going with the JWT authentication strategy, mostly because it’s super easy to set up and is fully supported by React-admin.

Enough talk, let's get started by installing the JWT auth extension library and Validatorjs on the Loopback API server.

npm i --save @loopback/authentication @loopback/authentication-jwt @types/validator

Next, bind the authentication components to the application class in src/application.ts

// src/appliation.ts

// ----------- Add imports -------------
import {AuthenticationComponent} from '@loopback/authentication';
import {
  JWTAuthenticationComponent,
  SECURITY_SCHEME_SPEC,
  UserServiceBindings,
} from '@loopback/authentication-jwt';
import {MongoDataSource} from './datasources';
// ------------------------------------

export class TodoListApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {

    //…

    // ------ Add snippet at the bottom ---------

    // Mount authentication system
    this.component(AuthenticationComponent);
    // Mount jwt component
    this.component(JWTAuthenticationComponent);
    // Bind datasource
    this.dataSource(MongoDataSource, UserServiceBindings.DATASOURCE_NAME);
    // ------------- End of snippet -------------
  }
}

Great job! We now have a foundation for auth.

Authentication usually works by validating the credentials of the user attempting to sign in and allowing him to go through if valid credentials are supplied. Thus, we’ll then need to create a user resource to represent a user. For our purposes, a user only has an id and an email field.

Alright, let’s create the user model using the Loopback CLI. Answer the CLI prompts as usual

lb4 model

11-user model.png

We’ll also need to create a controller for the user resource that handles all authentication logic. You can use the CLI to generate an empty controller.

Note that this controller would need to be an empty controller and not a REST controller
lb4 controller
12-user controller.png

The generated empty controller file can be found in src/controllers/user.controller.ts. Copy the contents of the file linked here into your controller file. It contains all the authentication logic. You can find the file here

Visit the link above and copy its contents into the user.controller.ts file

Finally, we can secure the customer resource by adding the authentication strategy we just implemented to its controller. Here’s how to do it:

// src/controllers/order.controller.ts

// ---------- Add imports -------------
import {authenticate} from '@loopback/authentication';

// ------------------ Add auth decorator -----------
@authenticate('jwt') // <---- Apply the @authenticate decorator at the class level
export class CustomerController {
  //...
}

Do the same for the film and rental resources by adding the authentication strategy to their respective controller files.

And that’s it! Visiting the API playground on the browser http://localhost:4000/explorer/ you’ll notice we have a nice green Authorize button at the top of the page. We also now have signup and login routes to create user accounts and log in.

You’ll need to use this playground/explorer to create a new user

Now, let’s use this authentication on the React-admin dashboard.

Adding authentication to React-admin

Implementing authentication on the React-admin dashboard is fairly straightforward. We need an authProvider which is an object that contains methods for the authentication logic, and also a httpClient that adds the authorization header to every request made by the dashboard.

Create an Auth.js file in src/Auth.js that contains the authProvider method, and the httpClient function. Here’s what the content of the file should be

// src/Auth.js

export const httpClient = () => {
  const { token } = JSON.parse(localStorage.getItem('auth')) || {};
  return { Authorization: `Bearer ${token}` };
};

export const authProvider = {
  // authentication
  login: ({ username, password }) => {
    const request = new Request(
      process.env.REACT_APP_API_URL + '/users/login',
      {
        method: 'POST',
        body: JSON.stringify({ email: username, password }),
        headers: new Headers({ 'Content-Type': 'application/json' }),
      }
    );
    return fetch(request)
      .then((response) => {
        if (response.status < 200 || response.status >= 300) {
          throw new Error(response.statusText);
        }
        return response.json();
      })
      .then((auth) => {
        localStorage.setItem(
          'auth',
          JSON.stringify({ ...auth, fullName: username })
        );
      })
      .catch(() => {
        throw new Error('Network error');
      });
  },
  checkError: (error) => {
    const status = error.status;
    if (status === 401 || status === 403) {
      localStorage.removeItem('auth');
      return Promise.reject();
    }
    // other error code (404, 500, etc): no need to log out
    return Promise.resolve();
  },
  checkAuth: () =>
    localStorage.getItem('auth')
      ? Promise.resolve()
      : Promise.reject({ message: 'login required' }),
  logout: () => {
    localStorage.removeItem('auth');
    return Promise.resolve();
  },
  getIdentity: () => {
    try {
      const { id, fullName, avatar } = JSON.parse(localStorage.getItem('auth'));
      return Promise.resolve({ id, fullName, avatar });
    } catch (error) {
      return Promise.reject(error);
    }
  },
  getPermissions: (params) => Promise.resolve(),
};

Alright! Now let’s make use of the authProvider and httpClient in our app. Import authProvider and httpClient from ‘Auth.jsintoApp.jsand passhttpClientas a second parameter tolb4Provider. Then add an authProvider prop to theAdmincomponent and pass inauthProvider` as its value.

Simple and easy!

// ----------- Import Auth -------------
import { authProvider, httpClient } from './Auth';

//…

// ------------ Use httpClient and authProvider in the Admin component ---------
 //...

Save the files and head back to the browser and you’ll be greeted with a login screen. Fill in the email and password of your registered user and you’ll be taken to the customers’ table like before.

And that’s it! We now have a super-secured app! 💪

Deploy 🚀

We now have a fully functional admin dashboard with authentication. Lastly, I’ll like to walk you through deployment to your favourite cloud provider.

Since the API generated using Loopback is a standard Nodejs server, you can deploy your app to any Nodejs hosting provider i.e Heroku or Glitch. But note that you will need to move all packages under devDependencies to the dependencies section in your package.json file.

And for the React-admin dashboard, you can deploy it on any static hosting service i.e Netlify or Vercel. Don’t forget to replace the lb4Provider URL with that of your hosted backend.

What’s a Rich Text element?

The rich text element allows you to create and format headings, paragraphs, blockquotes, images, and video all in one place instead of having to add and format them individually. Just double-click and easily create content.

  • xvcmbmvkmnkmbknmbkmlnj
  • A rich text element can be used with static or dynamic content. For static content, just drop it

A rich text element can be used with static or dynamic content. For static content, just drop it into any page and begin editing. For dynamic content, add a rich text field to any collection and then connect a rich text element to that field in the settings panel. Voila!

  1. A rich text element can be used with static or dynamic content. For static content, just drop it into any page and begin editing. For dynamic content, add a rich text field to any collection and then connect a rich text element to that field in the settings panel. Voila!

How to customize formatting for each rich text

Headings, paragraphs, blockquotes, figures, images, and figure captions can all be styled after a class is added to the rich text element using the "When inside of" nested selector system.

ksnopirirfnb [aorewmb[oiewsn b[opebr
  1. then connect a rich text

dfbstjsrykmsry

Square
Try Appsmith
Debugging your apps in Appsmith with the Appsmith Debugger, part 2
27
September
2022
Product

Debugging your apps in Appsmith with the Appsmith Debugger, part 2

Debugging your apps in Appsmith with the Appsmith Debugger, part 2
Ayush Pahwa
0
 minutes ↗
#
product
#
errors
#
troubleshooting
#
debugger
Product
Meet the sidekicks, Logs and Inspect Entity

The first part of this teardown helped you see how the Error pane can save you hours in debugging and build better internal apps. In this one, let’s meet two seemingly innocuous features that can give you debugging super-powers when used right.

Logs

The Logs pane shows you everything logged by Appsmith and, like Errors, in lockstep with the sequence of code execution in your build. Borrowing from the experience of showing logs in general—in the browser console, from a shell, or on your favorite IDE—the Logs pane has four views for specific debugging use cases.

Post_5.jpg (1920×1080)

All Logs

This view shows you all logs timestamped by when we saw them in your Appsmith session. Updated a widget’s property? Wrote a new action to your GraphQL datasource? Ran a JS Object to concat two queries? It all gets logged, including the errors you see in the Errors pane, in a separate view called Error Logs. You will see how that can be useful in a GIF, pun intended.

The All Logs view can be a little overwhelming, though, and a bit of work when you have been at your build for a while. For easier tracking of relevant logs, use one of the three options below.

Post_6.gif (1440×810)

Errors Logs

Everything you learned about the Errors pane applies to this view, too, but there’s more to this view. Here's a likely scenario to show that.

State #1

You have a button to reload a table, presumably to refresh the data from your datasource.

Condition #1

You use the Button property, onClick, which runs the query to fetch the latest data into the table.

Scenario #1

Your query fails.

- On just the Error pane

  • You see just the error for the failing query. Although helpful, it doesn’t offer context for the before and after of the error.

- On the Error Logs pane under Logs

  1. You see logs for the Button click and the executed onClick event .
  2. Because the onClick property is binded to queries and JS Objects, you see the ones that are successfully executed and those that fail.
Error_Logs__Appsmith.gif (1440×810)

The triaging in our example above is especially useful when you have nested queries, several dependent bindings, and a more complex workflow overall.

Console Logs

console.log_in_the_Editor__Appsmith.jpg (1920×1080)

Just introduced in the Debugger, console methods in Appsmith help you see statements for just JS Objects and JavaScript bindings so much better than in the browser sub-window.

Set points in your code that you want to log statements at, view tabular data, or see groups for repeated errors.

System Logs

Post_7.jpg (1920×1080)

Automatically tracking all your interactions with Appsmith during build, System Logs show a helpful trail of activity by descending order of timestamp, especially useful when you want to go back in time or pivot from a point of failure to everything that led to it.

They show up for different situations and interactions for the type of entity you are working with.

With widgets, you see a log when you

  • Drag-and-drop a new widget on the canvas.
  • Update the widget’s properties
    Updating a property also updates all its dependent properties which then show up in System Logs.
Dependent_properties_updates_in_system_logs__Appsmith.gif (1280×720)
For example, when you update the tableData property, you also see its dependent properties like selectedRowIndex, filters, triggeredRowIndex, and so on.
  • Trigger events with an end-user action.
Trigger_events_with_an_end-user_action__Appsmith.gif (1280×720)
For example, when you are using an end-user action to store a value with storeValue or when you want a click-action to trigger an operation like an update or delete and are using onClick, you see them show up in System Logs.
  • Delete a widget from the canvas

With actions, you see them when you

  • Create a new datasource or a query
  • Update query properties like queryName, queryBody, queryConfiguration, and queryProperties.
  • Execute a query
Execute_a_query.gif (1440×810)
This can be either from query pane, running a plain REST API query, a JS Object, or via a widget’s bindings.
  • Delete a query

With JS Objects, you’ll see system logs when you

  • Create and update code inside JS Objects
  • Execute JS Objects
Execute_JS_Objects.gif (1440×810)

Just like errors, system logs are native to entities and have four parts to them.

Parts_of_a_system_log_line__Appsmith.jpg (1920×1080)

The timestamp

Logged as your entities are created, updated and deleted, these little breadcrumbs help you track back from when the error occurred to when it was last A-Okay.

Timestamped_logs_in_System_Logs.gif (1440×810)

The message

Useful during build, the message of the log answers two questions— what were you doing with an entity—creating it, updating it, deleting it—and what happened with your action—success or failure.

  • With widgets, outside of CRUD information, you also see event-specific info like onClick and showAlert linked to those widgets.
  • Queries and JS Objects are straightforward with start and end points that indicate if they were updated, ran, and failed.

The source

Like errors, a system log has two parts to its source—the entity’s name.the type of entity, e.g., SELECT1.TABLE1.WIDGET.

Redirect_from_an_Inspect_Entity_sub-window.gif (1440×810)
👌🏽 Appsmith Experience plug

Clicking the source from the logs takes you to the associated entity anywhere in Appsmith, be it a widget, a query, or a JS Object. Noice!

The response

This doesn’t always show, but when it does, it can be useful confirmation of a binding working, a query running successfully, or a JS Object executing completely.

  • For widgets, you see which properties are updated when you are configuring them and how.
    Say you’re updating the text widget’s background property and you don’t see it change on the canvas. Track the log to the response for a quick confirmation of that and troubleshoot the canvas next.
  • For queries, you’ll see two different logs—the start of a query run and the status of its execution.
    The first type of log will show you configuration details of the query—helpful to verify if the config matches the request.        

{
    "timeoutInMillisecond":10000
    "paginationType":"NONE"
    "encodeParamsToggle":true
    "body":"SELECT * FROM public."users" LIMIT 10;"
    "pluginSpecifiedTemplates":[
        0:{
            "value":true
        }
    ]
}

  • The second type will throw an error if the run fails. When the query runs successfully, it shows all the parameters that the query ran with and the time taken for the response.

{
	"response" : [...],
	"request" : {
		"actionId" "6321c1193668£71e£7caala2"
		"requestedAt" : 1663912830.640344
		"requestParams": {...}
}

  • With JS Objects, you see the response from the function as a JSON after an object is successfully run. This shows you how Appsmith handles the function while evaluating and running it and can be useful for spotting conflicts, undefined references, or troublesome variables.

Inspect Entity

Borrowing from a modern browser’s Inspect Element feature, Inspect Entity lets you see incoming and outgoing entities for any widget. These entities can be queries, JS Objects, or even other widgets.

Group_8480.png (1920×1080)
  • Incoming entities are those that fetch data from the datasource into the widget.
    For example, if the data on a table is populated by a Postgres query, you’ll see the query name under the Incoming entities column.
  • Outgoing entities are those that can specify the data that’s to be sent to the datasource in a typical CUD operation and then send it to your datasource.
    Say, a text widget is binded to a table's selectedRow property, you will see the text widget’s name under the Outgoing entities column.

The Inspect Entity pane lets you see dependencies for all your widgets on the canvas, especially useful if you have a medium-complex app with several widgets working off of each other. For example, when you have a parent widget or query that controls bindings on other dependent widgets---call them children widgets---, Inspect Entity can show you all those children when you click the parent and quickly take you to any one of them directly.

In combination with Errors, Logs and Inspect Entity round out the Debugger for several scenarios during build and save you hours in building an app end-users love. Try out the Debugger and let us know how you like it, what it's missing, and what we can improve. Our Discord is the best place for that feedback.

The Appsmith Debugger now supports Console methods
23
September
2022
Announcement

The Appsmith Debugger now supports Console methods

The Appsmith Debugger now supports Console methods
Rishabh Rathod
0
 minutes ↗
#
debugger
#
troubleshooting
#
console-methods
Announcement

For a while now, you have used and loved the Appsmith Debugger, nearly complete with a Error pane, system and error logs, and an entity inspector. We say nearly complete because it was missing one of the most popular debugging tools in a dev’s toolkit—console methods.

We are happy to announce the availability of console methods for both cloud users and self-hosters on v1.8.0.

“But, what is the Appsmith Debugger?”

Image_1.png (1920×1080)

Think of the Appsmith Debugger as a set of Chrome DevTools—like for Appsmith. It lives on the familiar 🐞 everywhere in Appsmith and

  • shows helpful error messages for bindings, queries, and variables
  • lets you inspect entity relationships
  • filters system and user logs

All of this is helpful when debugging unexpected API responses or app viewer experiences. Should you care to learn more, this post breaks down the debugger by each one of its features.

“Okay, and console methods are…”

Just one of the most popular ways of print debugging in modern browsers, console methods, exposed by the console API, are a set of functions that help you log the values of variables at set points in your code, messages, or even tabular data so you can investigate them in your browser’s debugging console.

Before today, you could use all supported browser console methods, but only in the browser’s dev tools sub-window. To any developer with their hands dirty with front-end code, the browser debugging subwindow is a necessary evil—a thousand lines of errors, messages, values, and steps that you would have to sift through. We are not going to say, “Looking for the literal needle in the haystack”, but you know you are thinking it.

“And the Appsmith Debugger has a console now?”

Yes! 🥳

So, instead of something like,

you now see,

Image_3.png (1920×1080)

Sweet? This gets sweeter.

Supported methods

  • log

Almost synonymous with console, the .log() method is one of the most popular ways to log a message or the values of variables defined in your Javascript.

It can also be used to show helpful messages or comments, say, the entry and exit points of functions.

Example


getUUID: () => {
		console.log("entry - getUUID function");
		let prefix;
		
		let d = new Date().getTime();
		console.log("new date created -", d);
		d += (parseInt(Math.random() * 100)).toString();
		console.log(d, "random number generated by getUUID")
		if (undefined === prefix) {
			prefix = 'uid-';
		}
		d = prefix + d;
		console.log("UUID created -", d);
		console.log("exit - getUUID function")
		return d;
	}

Result

Image_4.png (1920×1080)
  • error

the .error() method logs an error message to the Appsmith console, be it a a string like, “This is an error message” or the value of a function.

Say you've written a function and you suspect it’s returning an error., but you don’t know what kind. For unknown unknowns like this, `error` comes handy.

Example


checkTextWidget: () => {
		const element = Text1.text;
		if (element == "") {
			console.error("There is an error. The Text property is empty ");
		}
		return element;
	}

Result

Image_5.png (1920×1080)
  • warn

Jus as .error() aids error investigations, .warn() shows, well, warnings for known knowns. Some situations this can come in handy are,- When the evaluated value of binded data on a widget is not using the same datatype as the expected value- When widgets continue to use deprecated queries or functions- When the timezone used in a datetime functions doesn't match the browser’s

Example


selectDefaultValue: () => {
	 const defaultValue = Select1.selectedOptionValue;
		if (defaultValue == ""){
			console.warn("No values selected on Select1 widget ")
		}
		return defaultValue;
}

Result

Image_6.png (1920×1080)
  • table

table (.) just does what it says—logs a Table widget’s data in key-value pairs for rows as objects. While we support this in Appsmith, we are still working on a browser console-like table, especially as we make the Table feature-richer.

Example


table1DataFunc: () =>{
		const data = Table1.tableData;
		console.table(data)
}

Result

Image_7.png (1920×1080)

That’s it! You now have the power of the console right within in Appsmith. There are other useful views available under Logs and we'll talk about them in a follow-up to the Debugger teardown soon. Bookmark this page. Thank us later.

Debugging your app in Appsmith with the Appsmith Debugger, Part 1
20
September
2022
Product

Debugging your app in Appsmith with the Appsmith Debugger, Part 1

Debugging your app in Appsmith with the Appsmith Debugger, Part 1
Ayush Pahwa
0
 minutes ↗
#
product
#
errors
#
troubleshooting
#
debugger
Product

That title is a tongue twister, innit? Almost.

Here’s a meme that isn’t. It’s just the painful truth.

Debugging_is_like_being_lost_in_a_deser.jpg (749×500)

There is no perfect code, so you know debugging is inevitable, but it’s still a chore and is as crushing often times as the meme claims it is.

But, while debugging is inevitable, making it painful is optional, especially when you have the Appsmith Debugger. We have claimed we champion developer experience as many times as we could before without being brazen about it. We think. So, we thought some more and said, “Let’s prove the claim, too.”

“Wait, wait. What is the Appsmith Debugger?”

In 2021, we shipped the Appsmith Debugger, a set of Chrome DevelTools-like features that have helped you investigate and resolve errors in Appsmith.

We recorded a video for it in a series about the Debugger, talked about it in our docs, and referenced it enough times to make you groan about our obsession with errors. If this is the first you are hearing of it, get on our Discord so we can tell you some more about it.

Why we did this

Browser dev tools are as helpful as a magnet when looking for iron fillings in a pristine haystack. To the untrained eye, they can be downright criminal, too.

Browser_debugger.jpeg (960×506)
Source: Reddit

Sure, sure, they nest groups of errors and there are separate tabs for the console and the debugger, but meh! There’s a sea of error messages, system logs, console logs, and then there’s you swimming in it.

Before we shipped the debugger, you saw,

  • errors inside a widget's Property pane that floated on your canvas which probably already had several widgets
  • the Editor’s Response pane, which clubbed legit responses with errors

The Debugger solved several of those problems.

Post_8.jpg (1920×1080)

What’s the Debugger have

Available on app.appsmith.com and our self-hosted release images, it can be called by toggling the debug icon—the one that looks like a bug—on the bottom-right corner of your Appsmith screen or with CTRL/CMD +D.

Inside the Debugger, live three panes, Errors, Logs, and Inspect Entity, each with their own uses. In the first part of this two part post, we will break the Error pane down for you and see how it can save you hours over browser dev tools in debugging.

If you would much rather just learn about Logs and Inspect Entity, bookmark this post. We will link to Part 2 in five days. :-)

Errors

Borrowing from a browser’s dev tools sub-window but improving on it radically, the Error pane lists all errors that we see when you are building inside Appsmith. Familiar examples include syntax errors from JavaScript bindings, reference errors from queries, and datatype mismatch errors.

Errors in the pane are specific to an Appsmith entity. Translated from Appsmithlish, it means you see helpful error messages about a faulting widget, a rogue query, or a stubborn JS Object.

Untitled.gif (1440×810)
Example of a faulting widget and the error beaconing it
Untitled.gif (1440×810)
A JS Object error

  • These errors get logged to the pane in lockstep with the sequence of code execution in Appsmith.
  • The Error pane is the default view when working with widgets—most noticeable if you have the Debugger sub-window resized as in the pictures in purple—so you know what’s going wrong and where in real-time.
  • The Editor's Error Pane is smarter. It doesn’t automatically switch to the Error pane—Response is the default on this screen—when an error occurs. Instead, the Debug icon lights up in red with a numeric notification that’s like a running ticker for the number of errors the Debugger sees with your queries or JS Objects. Click it to open the Error pane.
  • Every error you see in the pane follows a template with a few helpful pieces of info to help you debug.
image_high.jpeg (1920×1080)
Numbers on this image correspond to bullets below. Images in sub-bullets below show what the sub-bullet talks about.

The timestamp

Logged as your code executes or a value evaluates with your widgets, these little breadcrumbs help you track back from when the error occurred to when last it was A-Okay.

The issue

Depending on the error type, you will see a couple different kinds of issues.

  1. With widgets, you’ll see the faulting widget property’s name. An example of this is the commonplace The value at tableData is invalid, occurring when the property tableData expects an Array<Object> datatype but you have an Array<List> instead.
  2. With queries, you see more specific errors, often specific to the datasource you are running your queries to, often indicated by status codes returned by your failing requests.
  3. With JS Objects, we straight-up level with you about the parseability of your functions. Parseability probably isn’t a word, but you know what we mean.

The source

This has two parts to it—the entity’s name.the type of entity the troublesome one is, e.g., SELECT1.WIDGET. As is obvious and has been to you, SELECT1 is the entity’s name and WIDGET is the entity type.

👌🏾 Appsmith Experience plug: Clicking the source takes you to the faulting entity anywhere in Appsmith, be it a widget, a query, or a JS Object. Noice!

The message

This is the most helpful part of the message, beginning with Error and ending with a helpful bit of text or a number.

  1. Because widgets bind to queries or JS Objects using JavaScript, quite a few errors you see are the same as familiar JavaScript errors like SyntaxError or TypeError. Some other errors show is not defined. This is when a variable, a query, or a JS Object isn’t defined, but you have specified it in the Property pane.
  2. In the Editor, these messages go a step further and call out the line number in the editor that has the faulting code. For example, Line 2: Unrecognized token '$'. This type of message has three parts to it.
Post_9.jpg (1920×1080)

1. The type: Error

2. The string: relation “public.user” does not exit

3. The line number: Position 15

😻 Appsmith Experience plug: Clicking the message will open our in-app docs finder and run a helpful search to show you top docs matching the error.

Response from queries or bindings

This doesn’t always show, but when it does, it can show you helpful responses with query params or evaluated values of data bindings.

Post_10.jpg (1920×1080)
  1. With widgets, you’ll see the evaluated value from the bindings.
  2. With queries, you’ll see the payload from the API you are querying.

“How does all of this help?”

Consider two situations we have painfully drawn for you.

State #1

You have several queries and widgets on your way to a complete build.

Condition #1

You have nested queries inside JS Objects. Meaning, these queries are binded to multiple widgets via JavaScript transformations and have dependent parameters with each other.

Scenario #1

A query fails and returns an error.

Without the Appsmith Debugger

You decide to sift through the browser dev tools sub-window, trying to locate the faulty query in something that looks like ↓.

The_browser_console.png (1920×1080)

When you find the first problem query, you’re hoping against hope this is your patient zero.

  1. If so, congratulations aren’t quite in order yet. You’re still going to have to surgery the query to see what went wrong where.
  2. With browser tools, may you be lucky and find a fix in the first hour.

Most times, though, Murphy’s Law applies.

  1. Meaning, you will need to find the last problem query.
  2. Repeat steps #1 and #2 with all the sub-steps in between

If you have a friend who’s on Appsmith, you hear them say, “Good morning. Do you have a ready app? No? Try the Debugger. 🙄”

With the Appsmith Debugger

You see all the errors from all the failed queries In the Error pane and nothing else to crowd your investigation.

  1. You quickly scan by the type of errors.
  2. Errors are listed in the sequence of query execution.
Post_11.jpg (1920×1080)
So you can simply scroll to the first failed query, and investigate further.

  1. The error message tells you what failed with the params in which line, neatly indented neatly for you.

Don’t remember the query’s name? Pfft! We got it. Click the error message, and go right to the error source.

Trouble troubleshooting? Click the error message and find super-relevant docs in Appsmith’s doc finder.

At the end of it, you save a whole night’s hair-pulls, wake up bright and fresh, sip your coffee, and wonder why some people still use browser dev tools. 🤔 Maybe you should refer them to us.

State #2

You have the data from a REST API and the table for your dashboard, but you have left the chart for the very end. You are sensible like that. Charts are tricky things in general.

Condition #2

You have to bind the chart widget from Fusion Charts or one of our defaults with a query that should output the format Array<{ x: string, y: number Required }> as input to the widget. This will need JavaScript transformations.

Scenario #2

You get a datatype mismatch error.

Without the Appsmith Debugger

You toggle around the floating EXPECTED STRUCTURE, EXPECTED STRUCTURE - EXAMPLE, and EVALUATED VALUE panes to understand the chart widget’s configuration.

You have a JS Object for the transformation, so you now switch back and forth between the canvas and the JS Editor for each possible fix in the JS code.

  1. By now, you have console.loged your way to the browser tools sub-window. Magnet, meet Iron Fillings In A Haystack.
  2. Forgot the change you made to the JS Object five tries ago? Yeah, well, no System Logs, so what can you do, right? Maybe note each change on Sublime or VS Code from this point on.

With the Appsmith Debugger

Post_12.jpg (1920×1080)

Right after you run the transformation, you see the floating-pane-that-we-don’t have-a-name-for-yet show you some red and the Error pane light up with all your errors, timestamped and sequenced by the order of code execution.

  1. You see the type of error and the evaluated value for the faulting entity. Stick to this without worrying about the unnamed floating pane.
  2. Your query has trouble getting a response from your datasource, so you see that error, but hey, you also see the binding failure of that same query with the widget.
  3. No hunting for the query or the widget you want to troubleshoot. One click from the Debugger and you are transported to the associated entity.
Debugger_with_click-actions__JS_Editor.jpg (1920×1080)

You see all the errors from the transformation in one pane with click-actions for each one of them.

Docs_finder_from_Response__Appsmith.gif (1440×810)

Error messages not enough? Click the error and choose, Browse code snippets, and voila! You now now search for the chart + the query right there and see some of our helpful docs.

Made it to here? Your life inside Appsmith is going to change.

Also, this is just part one of this two-part breakdown. What’s next?

https://media.giphy.com/media/3kIGmlW0lvpnmF3bGy/giphy.gif

Better than post-credits. A whole other movie featuring Logs and Inspect Entity. Meanwhile, here’s a few things you can do.

Until the next Debugger post, Appsmiths.

P.S.: We love you.