Reader small image

You're reading from  Enterprise React Development with UmiJS

Product typeBook
Published inMay 2022
Reading LevelIntermediate
PublisherPackt
ISBN-139781803238968
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Douglas Alves Venancio
Douglas Alves Venancio
author image
Douglas Alves Venancio

Douglas has a background in systems analysis and development, his passion is to help customers and the community solve problems. Over the past few years, he has mainly worked with digital products and innovation, delivering the best user experience with modern web applications.
Read more about Douglas Alves Venancio

Right arrow

Chapter 3: Using Models, Services, and Mocking Data

One of the main features of a frontend web application is communication with the backend. Our application needs to collect user input and send it for processing.

In this chapter, you will learn how to define data by creating typescript interfaces and column definitions for the ProTable component. You will learn how to simulate the backend logic and data using Umi mock files. You will know how to send HTTP requests using the umi-request library. You will also learn to share states and logic between components using models.

We'll cover the following main topics:

  • Defining response types and column types
  • Creating the opportunity details page
  • Simulating data and API responses
  • Sending HTTP requests with Umi request
  • Using models for sharing states and logic

By the end of this chapter, you'll have learned how the data flow works in Umi and how to organize your projects using the services and...

Technical requirements

To complete this chapter's exercises, you only need a computer with any OS (I recommend Ubuntu 20.04 or higher) and the software installed in Chapter 1, Environment Setup and Introduction to UmiJS (Visual Studio Code, Node.js, and Yarn).

You can find the complete project in the Chapter03 folder in the GitHub repository available at https://github.com/PacktPublishing/Enterprise-React-Development-with-UmiJs.

Defining response types and column types

In this section, we will create TypeScript interfaces to define the data that we'll receive from the backend and create column definitions for the ProTable component on each page.

Let's start with the interfaces. Follow these steps to create the TypeScript interfaces:

  1. Let's first create the folder for definition files. Under the src folder, create a new folder called types.
  2. Now, in the types folder, create a new file named user.d.ts and add the following interface code:
    export interface User {
      id?: number;
      name?: string;
      company?: string;
      role?: {
        id: number;
        title: string;
      };
      isLoggedIn: boolean;
    }

The User interface defines how we'll receive user information from the backend.

  1. Create a new file in the types folder named customer.d.ts and add the following interface:
    export interface...

Creating the opportunity details page

In this section, we'll create the opportunity details page. The opportunity details page allows the user to track and register opportunity activities.

The user can also change the opportunity step and edit the opportunity properties such as title and expected revenue.

Follow these steps to create the opportunity details page:

  1. Run the following command to generate the opportunity detail page:
    yarn umi g page /OpportunityDetail/index --typeScript --less
  2. We'll use a pro component called ProDescriptions. It's similar to the ProTable component but intended for display properties instead of a batch of data. Run the following command to add the ProDescriptions component to the project:
    yarn add @ant-design/pro-descriptions@1.10.5
  3. Next, import these dependencies to the index.tsx file in the OpportunityDetail folder, as follows:
    import { Opportunity } from '@/types/opportunity';
    import ProDescriptions from &apos...

Simulating data and API responses

In this section, you'll learn how to create mock files to simulate backend logic and API responses.

Mock files are helpful to decouple frontend development from backend development, as you don't need the backend ready to make requests and populate your interface with data.

A mock file is simply a JavaScript object with endpoint route definitions and a response to each endpoint. Consider the following example:

export default {
  'GET /api/products': { total: 0, products: [] },
};

In this example, when the project is running, we can send an HTTP GET request to http://localhost:8000/api/products to receive the object defined in the mock file.

Umi will registry all files with the .js and .ts extensions inside the mock folder as mock files.

Now that we know how mock files work, let's create mock files for our application. Follow these steps:

  1. In the project root directory, create a new folder...

Sending HTTP requests with Umi request

In this section, we'll develop the requests to the backend using the umi-request library.

We'll create all the requests in separate files inside the services folder for each context. This organization helps us clean the components' code and reuses the requests over the interfaces.

For sending HTTP requests, we'll use Umi request. This is a library based in the fetch and axios libraries that is simple to use and provides common features such as error handling and caching. Consider the following example:

request<Product>('/api/products', {
  method: 'POST',
  headers: { Authorization: 'Bearer eyJhbGciOi...' },
  params: { onSale: true },
  data: {
    id: 0,
    title: 'My product',
    price: 10.0,
  },
});

The request function requires two main parameters –...

Using models for sharing states and logic

In this section, we'll create models for sharing states and logic between components.

A model is a special custom React hook to centralize the states and logic for a specific context.

We must create the models' files inside the src/models folder, and we can access these models using the useModel custom hook, as follows:

const { currentUser } = useModel('user');

Here, the user namespace matches the model filename, so the model file must be named user.ts.

Let's create the customer model and the opportunity model to demonstrate the use of models. These two models will contain the logic and result for creating, reading, and updating operations and share these operations between different interfaces.

Follow these steps to create the models:

  1. Create a new folder called models inside the src folder.
  2. Next, create a new file named customer.ts under the models folder and add the following:
    import...

Summary

In this chapter, we created the definition files for all the backend data and created the ProTable column definitions on each page. We created the opportunity details page using the ProDescritions component and the Activity interface to describe the opportunity activities.

You learned how Umi mock files work and how to create mock endpoints to provide simulated backend data and logic by creating the mock files for our application. Next, you learned how to organize your application requests using the services folder and send requests using the umi-request library by creating the services files for our application. Finally, you learned how models work and created the customer and opportunity models to share logic and state between components.

In the next chapter, you will learn how to handle API error responses by configuring the umi-request library, protecting routes using plugin-access, and storing and globally accessing user information after login.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Enterprise React Development with UmiJS
Published in: May 2022Publisher: PacktISBN-13: 9781803238968
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Douglas Alves Venancio

Douglas has a background in systems analysis and development, his passion is to help customers and the community solve problems. Over the past few years, he has mainly worked with digital products and innovation, delivering the best user experience with modern web applications.
Read more about Douglas Alves Venancio