Skip to main content

Ionic & Vue Sample Application Using Vuex State Management

In this article, we are going to create a sample application of Ionic & Vue our main target is to implement Vuex State Management.

Create A Sample App Of Ionic5 Using Vue :

To begin to create an Ionic application, we should have the Ionic CLI installed in our system environment.
Command to install latest Ionic CLI:
npm install -g @ionic/cli@latest
Now run the following command to create Ionic5 using the Vue application.
Command to create Ionic Vue application
ionic start your_app_name blank --type vue
Now run the following command to install Vuex into our Ionic&Vue app.
Vuex Command
npm install vuex@next --save

TypeScript Or Javascript:

By default Ionic sample created with the support of TypeScript in any library like angular, react, and vue. Typescript can be chosen to develop our application. But in the case of Vue most of the developers or preferred to choose javascript syntax instead of Typescript for application development. So to make our Ionic Vue application use javascript we need to remove few Typescript references, so follow the below steps.
  • Remove TypeScript dependencies.
command to unistall the typescript dependencies
npm uninstall --save typescript @types/jest @typescript-eslint/eslint-plugin @typescript-eslint/parser @vue/cli-plugin-typescript @vue/eslint-config-typescript
  • We need to change the file extensions from ".ts" to ".js", we mostly have 2 '.ts files' like 'main.ts' and 'router/index.ts'.
  • In the '.eslintrc.js' file needs to remove the '@vue/typescript/recommended' from the 'extends' array property and next need to remove the @typescript-eslint/no-explicit-any': 'off' property from the rules object.
  • Now remove the 'Array<RouteRecordRaw>' type in 'router/index.js'.
  • Delete the 'shims-vue.d.ts' file.
  • Remove the 'lang="ts"' attribute on script tag in our '.vue' files like 'App.vue' and 'view/Home.vue'.

Create Pages Vue Component:

Before creating our pages vue component let's restructure our project template like:
  • Delete the 'views/Home.vue' and 'views' folder.
  • Remove the 'Home.vue' route and its configuration from the 'router/index.js' file.
Now let's create a page vue component like 'Users.vue'.
pages/Users.vue:
<template>
  <div>
    <h4>My Users Page</h4>
  </div>
</template>
<script>
export default {};
</script>
Configure route to our 'Users.vue' component.
src/router/index.js:
import { createRouter, createWebHistory } from "@ionic/vue-router";
import Users from "../pages/Users.vue";

const routes = [
  {
    path: "/",
    redirect: "/users",
  },
  {
    path: "/users",
    component: Users,
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

export default router;

Add Master Layout Vue Component:

Now we have to define a master template for our application which will be applied for all the pages. The core ionic components to define the layout vue component are like:
  • IonPage
  • IonHeader
  • IonContent
  • IonTitle
  • IonToolbar
Let's create a master layout for our sample.
src/components/MasterLayout.vue:
<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-title>{{ pageTitle }}</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content>
      <slot> </slot>
    </ion-content>
  </ion-page>
</template>
<script>
import {
  IonPage,
  IonHeader,
  IonContent,
  IonToolbar,
  IonTitle
} from "@ionic/vue";
export default {
  components: {
    IonPage,
    IonHeader,
    IonContent,
    IonToolbar,
    IonTitle,
  },
  props: ["pageTitle"],
  
};
</script>
<style scoped>
ion-toolbar{
    --background: var(--ion-color-primary);
    --color: var(--ion-color-primary-contrast)
}
</style>
  • Here we have defined our master template using the Ionic core components. 
  • The '<slot>' tag is the area in which our routed page content will be rendered. 
  • The page title of each page will be passed dynamically using the input properties using the 'props'.
  • Applied some styles to our 'ion-toolbar' component.
Now let's register our 'MasterLayout.vue' globally in the main.js file
src/main.js:
import MasterLayout from './components/MasterLayout.vue';
// code hidden for display purpose
app.component('master-layout',MasterLayout);  
Now update our 'Users.vue' component to use 'MasterLayout.vue'.
src/pages/Users.vue:
<template>
  <master-layout pageTitle="Users">
    <div>
      <h4>My Users Page</h4>
    </div>
  </master-layout>
</template>
<script>
export default {};
</script>

Vuex Core Building Blocks:

Actions: Actions are task performers which have the capabilities to do either synchronous or asynchronous operations. In Vuex actions are used to invoke the rest API's to fetch the data and then actions call mutations to change the store state. To invoke mutations actions use a command called 'commit'. This 'commit' command invokes appropriate mutation and receives the rest API data as input to save into the store state.

Mutations: Mutations are to perform mutable operations. In Vuex the only option to change the state of the store is to use mutations. So the only way to add or update the data of the Vuex store is done by mutations.

State: State is a simple javascript object literal. A Vuex store saves or holds the data in the state object.

Getters: Getters are to perform tasks to retrieve the data from the Vuex store state. Getters are helped to retrieve data and then we can bind the data to components. So using these Getters in n-number of Vue Components can share the same data from the Vuex store.

Setup Vuex Store:

Let's begin to set up the vuex store into our sample application where all data will be provided from this store to our application.
Our store folder structure looks as below
Let's create a store module for our users as below:
src/store/modules/user.js:

const state = () => ({

});

const getters = {};

const actions = {};

const mutations = {};

export default{
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}
  • (Line: 1-3) The 'state' stores all data.
  • (Line: 5) The 'getters' contains all the functions are methods to fetch the data from the 'state'.
  • (Line: 7) The 'actions' are to perform async jobs like calling API.
  • (Line: 9) The 'mutations' contain a function that has the capability to modify the 'state'.
  • (Line: 12) Enabled namespace for our store while invoking 'getters' or 'actions' or 'mutations' we need specify the namespace. This namespace value is equal to the property name of the module where our store will register in upcoming steps.
Now register our 'users' store as one of the store modules.
src/store/index.js:
import userModule from './modules/users';
import {createStore} from 'vuex';

const store = createStore({
    modules:{
        users: userModule
    }
});

export default store;
  • Here we registering our store as a module to the property 'users'. Theis 'users' property name will be used as a namespace.
Now integrate our store into the vue instance pipeline in main.js file.
src/main.js:
import store from './store/index';
// code hidden for display purpose
app.use(store);

Rest API:

In our sample for displaying some users data, I will be going to consume free rest API like "https://jsonplaceholder.typicode.com/users".

Its response result looks as below:

Create Store Action That Going To Invoke Endpoint:

First, install the 'Axios' library for consuming the rest calls.
Command To Install Axios
npm install axios
Now let's create an action method that will consume the rest API.
src/store/modules/user.js: 
const actions = {
    async fetchUsers(){
       var response =  await axios.get("https://jsonplaceholder.typicode.com/users");
       console(response.data);
    }
};

Create a Store Mutation To Update Store State:

Let's create a property to hold the data in the store state.
src/store/modules/users.js:
const state = () => ({
    users:[]
});
Now create a mutation method to update the store state.
src/store/modules/users.js:
const mutations = {
    saveAllUsers(state, payload){
        state.users = payload;
    }
};
  • Here first parameter 'state' automatically passed by the framework, second parameter 'payload' data to store the data into the store.
Now update our action method to invoke the mutation method.
src/store/modules/users.js:
const actions = {
    async fetchUsers({commit}){
       var response =  await axios.get("https://jsonplaceholder.typicode.com/users");
       commit('saveAllUsers', response.data);
    }
};
  • Here 'commit' input parameter automatically passed to the action method by the vuex. The 'commit' command is used to invoke the mutation. The first input parameter is the name of the mutation method and the second method is to save the payload.

Create A Getter Method To Fetch Users:

Now let's implement a 'getter' method to fetch all users from the store state as below.
src/store/modules/users.js:
const getters = {
    allUsers(state){
        return state.users;
    }
};

Users Page Access Data From The Store:

Now on our user's page, we need to display the data by accessing it from the store.
src/pages/Users.vue:(Html Part)
<template>
  <master-layout pageTitle="Users">
    <div>
      <ion-button expand="full" @click="showUsers()">Show Users</ion-button>
      <ion-card v-for="user in allUsers" :key="user.id">
        <ion-card-content>
          <ion-card-title>{{user.name}}</ion-card-title>
        </ion-card-content>
        <ion-item>
          <ion-label>Email</ion-label>{{user.email}}
        </ion-item>
      </ion-card>
    </div>
  </master-layout>
</template>
  • (Line: 4) The button invokes the method for calling the rest API.
  • (Line: 5-12) The ion-card' component displays the user's data.
src/pages/Users.vue:(Script Part)
<script>
import {mapGetters,mapActions} from 'vuex';
import {IonButton, IonCard, IonCardContent, IonCardTitle, IonItem, IonLabel} from '@ionic/vue';
export default {
  components:{
    IonButton,
    IonCard,
    IonCardContent,
    IonCardTitle,
    IonItem,
    IonLabel
  },
  computed:{
    ...mapGetters('users',{
      allUsers:'allUsers'
    })
    
  },
  methods:{
    ...mapActions('users',{
      fetchUsers:'fetchUsers'
    }),
    async showUsers(){
      await this.fetchUsers();
    }
  }
};
</script>
  • (Line: 2) Importing the 'mapGetters' and 'mapActions' from 'Vuex'.
  • (Line: 3) Imported all required ionic components for our page display.
  • (Line: 14-16) Using the 'mapGetters' method registering the store getter method. Since getters are to fetch the data, so getters should be registered inside of the 'computed' properties which listen for the latest changes. Here the first parameter of 'mapGetters' is namespace('users' is namespace).
  • (Line: 20-22) Using the 'mapActions' method registering the store action method. Since actions are to invoke the API call, so getters can be registered inside of the 'methods' property.
  • (Line: 23-25) Triggering the action method on clicking the button.

Create Store Action And Mutation For Create User:

Now let's create action and mutation for the create user to our sample
src/store/modules/users.js:
const actions = {
    async addUser({commit}, payload){
        // since our rest api only support get
        // here we simply update the store state
        commit('addUser', payload);
    },

};

const mutations = {
   
    addUser(state,payload){
	// this line of code is fake , when we have save no nedd to write this line
        payload.id = (state.users.length + 1);
        state.users.unshift(payload);
    }
};
  • (Line: 2-6) Action method for creating a new user. Here we don't have a post endpoint so for demo purposes we just going to store data to the state.
  • (Line: 12-16) Mutation to adding our new record to 'users' state.

Create A Store Getters, Actions, And Mutations To Update User:

let's write some logic for store getters, actions, and mutations to update the records.
src/store/modules/user.js:
const getters = {
    userById(state){
        return (id) => {
            return state.users.find(u => u.id == id);
        }
    }
};

const actions = {
    async updateUser({commit}, payload){
         // since our rest api only support get
        // here we simply update the store state
        commit('updateUser', payload);
    }
};

const mutations = {
    updateUser(state, payload){
        let filteredUsers = state.users.filter(u => u.id !== payload.id);
        filteredUsers.unshift(payload);
        state.users = filteredUsers;
    }
};
  • (Line: 2-6) The getter method to fetch the filtered user. This getter will be used for updating the record.
  • (Line: 10-14)The action method needs to trigger the update API and then invoke mutation to store the latest data(For our sample we don't have API to update).
  • (Line: 18-22) The mutation method of updating our new data into the store.

Add Or Update Page Vue Component:

Now we will create a page vue component that will be used for both add or update the user based on the route that contains the user's id. If in the route users id we got '0' then we need to consider it for adding the new record else if the user id we got greater than the '0' then we need to consider it for updating the record.
src/pages/AddOrUpdateUsers.vue:(Html Part)
<template>
  <master-layout :pageTitle="pageTitle">
    <ion-card>
      <ion-card-header>
        <ion-card-title></ion-card-title>
      </ion-card-header>
      <ion-card-content v-if="userInfo">
        <ion-item>
          <ion-label position="floating">User Name</ion-label>
          <ion-input v-model="userInfo.name"></ion-input>
        </ion-item>
        <ion-item>
          <ion-label position="floating">Email</ion-label>
          <ion-input v-model="userInfo.email"></ion-input>
        </ion-item>
        <ion-button expand="full" @click="saveorupdate()">{{
          btnText
        }}</ion-button>
      </ion-card-content>
    </ion-card>
  </master-layout>
</template>
  • (Line: 2) The 'pageTitle' property of dynamic value which will display different page title on rendering.
  • Here we created a small form inside of the 'ion-card' this form will be used for both adding and editing the user records.
  • The property 'userInfo' is used for the model binding.
  • The 'saveorupdate()' callback method registered for the button.
  • (Line: 17) Displaying button text dynamically.
src/pages/AddOrUpdateUser.vue:
<script>
import { mapActions, mapGetters } from "vuex";
import {
IonCard,IonCardHeader,IonCardTitle,IonCardContent,IonItem,IonLabel,IonInput,IonButton,
} from "@ionic/vue";
export default {
  components: {
    IonCard,IonCardHeader,IonCardTitle,IonCardContent,IonItem,IonLabel,IonInput,IonButton,
  },
  data() {
    return {
      userInfo: null,
      routeId: this.$route.params.id,
      btnText: "",
      pageTitle: ""
    };
  },
  computed: {
    ...mapGetters("users", {
      userById: "userById",
    }),
  },
  mounted() {
    if (this.routeId == 0) {
      this.userInfo = {
        id: 0,
        name: "",
        emai: "",
      };
      this.btnText = "Add User";
      this.pageTitle = "Create A User";
    } else {
      this.userInfo = this.userById(this.routeId);
      this.btnText = "Update User";
      this.pageTitle = "Update A User";
    }
  },
  methods: {
    ...mapActions("users", {
      addUser: "addUser",
      updateUser: "updateUser",
    }),
    saveorupdate() {
      if (this.userInfo.id == 0) {
        this.addUser(this.userInfo);
        this.$router.push("/users");
      } else {
        this.updateUser(this.userInfo);
        this.$router.push("/users");
      }
    },
  },
};
</script>
  • (Line: 13) Fetching the user id from the route.
  • (Line: 19-21) Registered the 'userById' getter method.
  • (Line: 23-36) If the new user that is user 'id' is zero then just assign empty data to the 'userInfo' object and also assign 'pageTitle', 'btnText' values that represent adding record. If the user 'id' greater than zero means updating the record then we will assign 'userInfo' object data from the 'userById' getter method.
  • (Line: 39-42) Registering the action methods like 'addUser' and 'updateUser'.
  • (Line: 43-51)Logic to invoke 'addUser' or 'updateUser'.
Now configure the route.
src/router/index.js:
import AddOrUpdateUser from "../pages/AddOrUpdateUser";

const routes = [
  {
    path: "/add-or-update/:id",
    component: AddOrUpdateUser
  },
];

Buttons Like Add, Edit, And Delete:

Now let's add buttons in our User.vue page component.
src/pages/User.vue:(Html Part)
<template>
  <master-layout pageTitle="Users">
    <div>
      <ion-button expand="full" @click="showUsers()">Show Users</ion-button>
      <ion-card v-for="user in allUsers" :key="user.id">
        <ion-card-content>
          <ion-card-title>{{ user.name }}</ion-card-title>
        </ion-card-content>
        <ion-item> <ion-label>Email</ion-label>{{ user.email }} </ion-item>
         <ion-item> 
           <ion-buttons>
             <ion-icon @click="edit(user.id)" :icon="create" slot="end"></ion-icon>
             <ion-icon :icon="trash" slot="end"></ion-icon>
           </ion-buttons>
        </ion-item>
      </ion-card>
    </div>
    <template v-slot:footerdata>
      <ion-fab vertical="bottom" horizontal="end">
        <ion-fab-button routerLink="/add-or-update/0">
          <ion-icon :icon="add"></ion-icon>
        </ion-fab-button>
      </ion-fab>
    </template>
  </master-layout>
</template>
  • (Line: 12) Edit button on each card registered with the 'edit' callback method.
  • (Line: 18-24) Added template with slot based rendering on the MasterLayout.vue. This template contains 'ion-fab-button' that will navigate us to 'AddOrUpdateUser.vue' with the user id in the URL as '0'.
src/pages/User.vue:(Script Part)
<script>
import { mapGetters, mapActions } from "vuex";
import {
  IonButton,IonCard,IonCardContent,IonCardTitle,IonItem,IonLabel,IonFab,IonFabButton,IonIcon,IonButtons
} from "@ionic/vue";
import { add, create,trash } from "ionicons/icons";
export default {
  components: {
    IonButton,IonCard,IonCardContent,IonCardTitle,IonItem,IonLabel,IonFab,IonFabButton,IonIcon,IonButtons
  },
  computed: {
    ...mapGetters("users", {
      allUsers: "allUsers",
    }),
  },
  methods: {
    ...mapActions("users", {
      fetchUsers: "fetchUsers",
    }),
    async showUsers() {
      await this.fetchUsers();
    },
    edit(id){
      this.$router.push(`/add-or-update/${id}`);
    }
  },
  data() {
    return {
      add,
      create,
      trash
    };
  },
  
};
</script>
  • (Line: 23-25) Navigating to the update page by passing user-id dynamic value.
  • (Line: 27-33) Loading the 'ion-icons'
Now in the master layout add 'ion-footer' and inside of creating slot to render our 'ion-fab-button'.
src/components/MasterLayout.vue:
// code hidden for display purpose
<template>
  <ion-page>
    <ion-footer>
        <slot name="footerdata"></slot>
    </ion-footer>
  </ion-page>
</template>
<script>
import {
} from "@ionic/vue";
export default {
  components: {
    IonFooter
  }
</script>


Create Action And Mutation For Deleting User:

Now let's create store action and mutation for deleting the user.
src/store/modules/user.js:
const actions = {

    async deleteUser({commit}, id){
         // since our rest api only support get
        // here we simply update the store state
        commit('deleteUser', id);
    }
};

const mutations = {
    deleteUser(state, id){
        state.users = state.users.filter(u => u.id !== id);
    }
};
  • The action method needs to call API and then invoke the mutation to update the state.
  • Mutation here removing the item match for the 'id' value from the state.

Update User.vue Delete Button:

Now in our User.vue page component update delete logic.
src/pages/User.vue:
// code hidden for the display purpose
<ion-icon @click="edit(user.id)" :icon="create" slot="end"></ion-icon>
<script>

export default {
  methods: {
    ...mapActions("users", {
      fetchUsers: "fetchUsers",
      deletUserAction: "deleteUser"
    }),
    deleteUser(id){
      this.deletUserAction(id);
    }
  },

};
</script>
  • Registered 'deleteUser' store action method and used inside of the delete callback method to remove the item from the state.

Test In Android Emulator:


Few sample screenshots of our sample from the android emulator.



That's all about the Ionic&Vue sample application using the Vuex state-management.

Support Me!
Buy Me A Coffee PayPal Me 

Wrapping Up:

Hopefully, I think this article delivered some useful information about Vuex State Management with int the Ionic&Vue Application. I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

Popular posts from this blog

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route. An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaul

Asp.Net Core MVC Form Validation Techniques

Introduction: Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library  jQuery Validate . In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples. Getting Started: Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio. Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as bel

.NET Core MVC Application File Upload To Physical Location With Buffered Technique

Buffering Technique In File Upload: The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client.  Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file.  Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk.  If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading. In the following article, we create a sample for the file uploading using .NET Core MVC application. Create The .NET Core MVC Project: Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below.   Check the link to use the Visual Studio Code for .NET Core Application . IFormFile: Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files f

Ionic Picker Sample Code In Angular

Introduction: Ionic Picker(ion-picker) is a popup slides up from the bottom of the device screen, which contains rows with selectable column separated items. The main building block of ion-picker as follows: PickerController PickerOptions PickerController: PickerController object helps in creating an ion-picker overlay. create(opts?: Opts): Promise<Overlay> PickerController create method helps in create the picker overlay with the picker options PickerOptions: PickerOptions is a configuration object used by PickerController to display ion-picker. Single Column Ionic Picker: single.item.picker.ts: import { Component } from "@angular/core"; import { PickerController } from "@ionic/angular"; import { PickerOptions } from "@ionic/core"; @Component({ selector: "single-column-picker", templateUrl:"single.item.picker.html" }) export class SingleItemPicker { animals: string[] = ["Tiger&quo

GraphQL API Integration In Asp.Net Core Application

Introduction: GraphQL is a query language for your API and a server-side runtime for executing queries by using a type system you define for your data. GraphQL can be integrated into any framework like ASP.NET, Java, NestJs, etc and it isn't tied to any specific database or storage engine and is instead backed by your existing code and data. How GraphQL API Different From Rest API: GraphQL exposes a single end-point or route for the entire application, regardless of its responses or actions. HTTP-POST is the only Http verb recommended by the GraphQL. The client applications (consumers of API) can give instructions to GraphQL API about what type of properties to be returned in the response. Building Blocks Of GraphQL API: The main building blocks of GraphQL API is Schemas and Types.  A 'Schema' in GrpahQL API describes the functionality available to the clients connect to API. Schema mostly consists of GraphQL Object Types, Queries, Mutations, etc. T

ASP.NET Core Web API Versioning

Introduction: An iteration and evolutionary changes of an ASP.NET Core Web API is handled by Versioning. Versioning of an API gives confidence to the clients which consumes API for a long time. Any changes or development of an API will be accessible using the new version and it won't cause issues to the clients consuming the old version of API. When To Use Versioning: Any API response changes. Developing an API by implementing testing levels like 'Alpha', 'Beta', and 'RC' versions before releasing Production. Deprecating an API which means API going to be removed or upgraded by a version within a short period. Versioning Types: Query String Versioning Url Path Versioning Media Type Versioning API Version Nuget: To Configure versioning to AspNet Core Web API Microsoft provided a library(Microsoft.AspNetCore.Mvc.Versioning). So to use the versioning library please install NuGet below.              Install-Package Microsoft.A

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

.Net Core HttpClient JSON Extension Methods Using System.Net.Http.Json Package

.Net Core 3.0 onwards Microsoft brought up a new package called System.Net.Http.Json. This new package provides JSON extension methods for HttpClient. These JSON extension methods will have a prebuild mechanism for serializing or deserializing response data or payload of HttpClient call. System.Net.Http.Json extension methods that are provided to HttpClient, few of them are mentioned below. GetFromJsonAsync PostAsJsonAsync PutAsJsonAsync ReadFromJsonAsync In this article, we understand System.Net.Http.Json package by implementing the HttpClient samples by with and without JSON extension methods and compare them. Create A .Net Core Web API Sample Application: Let's create a .Net Core sample Web API application, from this application we will consume another Web API by implementing HttpClient calls. We can create a Web API sample application using IDE like Visual Studio 2019(Supports .Net Core 3.0 plus) or  Visual Studio Code . Create A Typed Client: In .Net Core using the Http

Blazor Server CRUD Operations

Introduction: Blazor Server is a web framework to develop server-side single-page applications. Blazor is made up of components with the combinations on C#, Html, CSS.  Blazor Server is production-ready from the .Net Core 3.0.  Blazor Server Working Mechanism: Blazor Server is a very light-weight web development framework.  In Blazor Server, not all code gets downloaded to the client browsers. Blazor Server made of components these components can be a block of code or page with respective navigation.  Blazor server application communicates with the server with a SignalR background connection which is inbuilt functionality. Application click,  form submission, change events, application page navigation every operation is carried out by the SignalR connection by communicating with the server.  Blazor updates the Html DOM very gently on every data update without any overhead. Blazor Server application maintains a nice intelligent tree structure to update the required inform

NestJS API CRUD Operations With MongoDB

Introduction: NestJS is a framework used to develop server-side applications. NestJS built on top of Node.js frameworks like Express. It is a combination of Progressive Javascript, Object-Oriented Programming, Functional Programming, and Functional Reactive Programming. Nest CLI Installation: Using Nest CLI we are able to generate the NestJS starter project with the default template. To install Nest CLI globally over our system open command prompt and run the command               npm i -g @nestjs/cli Now create a sample project by using Nest CLI command              nest new your_project_name package.json: Now open the package.json file from the sample application created, you can observe few properties like "scripts", "dependencies", and "devDependencies". "dependencies" contains all plugins to be installed and used them to run the application. "devDependencies" contain all plugins to be installed and used them