DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

How to implement create & update details in React, Vue & Angular?

React

Implementing create and update operations with an API in React involves several steps. Below is a simplified guide using React Hooks and the fetch API. Make sure you have a backend API ready to handle these operations.

Let's create a simple example with a modal for creating and updating user details.

  1. Install Dependencies: Make sure you have React and any state management library you prefer (e.g., useState or useReducer). If not, you can create a new React app using Create React App.
   npx create-react-app my-react-app
   cd my-react-app
Enter fullscreen mode Exit fullscreen mode
  1. Create Components: Create two components, UserForm.js for the modal form, and UserList.js to display a list of users.
   // UserForm.js
   import React, { useState } from 'react';

   const UserForm = ({ onSave, onCancel, user }) => {
     const [name, setName] = useState(user ? user.name : '');

     const handleSave = () => {
       const newUser = { id: user ? user.id : null, name };
       onSave(newUser);
     };

     return (
       <div>
         <label>Name:</label>
         <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
         <button onClick={handleSave}>Save</button>
         <button onClick={onCancel}>Cancel</button>
       </div>
     );
   };

   export default UserForm;
Enter fullscreen mode Exit fullscreen mode
   // UserList.js
   import React from 'react';

   const UserList = ({ users, onEdit }) => {
     return (
       <ul>
         {users.map((user) => (
           <li key={user.id}>
             {user.name} <button onClick={() => onEdit(user)}>Edit</button>
           </li>
         ))}
       </ul>
     );
   };

   export default UserList;
Enter fullscreen mode Exit fullscreen mode
  1. App Component: In your App.js or main component, manage the state, handle API calls, and render the UserForm and UserList.
   // App.js
   import React, { useState, useEffect } from 'react';
   import UserForm from './UserForm';
   import UserList from './UserList';

   const apiUrl = 'https://your-api-url.com/users'; // Replace with your actual API URL

   const App = () => {
     const [users, setUsers] = useState([]);
     const [editingUser, setEditingUser] = useState(null);

     useEffect(() => {
       // Fetch initial user data from the API
       fetch(apiUrl)
         .then((response) => response.json())
         .then((data) => setUsers(data));
     }, []);

     const handleSave = (user) => {
       const method = user.id ? 'PUT' : 'POST';
       const url = user.id ? `${apiUrl}/${user.id}` : apiUrl;

       fetch(url, {
         method,
         headers: {
           'Content-Type': 'application/json',
         },
         body: JSON.stringify(user),
       })
         .then((response) => response.json())
         .then((savedUser) => {
           setUsers((prevUsers) =>
             user.id
               ? prevUsers.map((u) => (u.id === savedUser.id ? savedUser : u))
               : [...prevUsers, savedUser]
           );
           setEditingUser(null);
         });
     };

     const handleEdit = (user) => {
       setEditingUser(user);
     };

     const handleCancel = () => {
       setEditingUser(null);
     };

     return (
       <div>
         <h1>User Management</h1>
         <UserList users={users} onEdit={handleEdit} />
         <UserForm onSave={handleSave} onCancel={handleCancel} user={editingUser} />
       </div>
     );
   };

   export default App;
Enter fullscreen mode Exit fullscreen mode

Make sure to replace 'https://your-api-url.com/users' with the actual URL of your API endpoint.

  1. Run the App: Start your React app:
   npm start
Enter fullscreen mode Exit fullscreen mode

This is a basic example, and you might need to handle error scenarios, loading states, and other edge cases based on your application requirements. Additionally, consider using a state management library like Redux for more complex applications.

Vue

Below is an example of implementing create and update operations with an API in Vue.js. We'll use the Composition API and the axios library for making HTTP requests.

  1. Install Dependencies: Make sure you have Vue.js and the axios library installed. If not, you can create a new Vue.js app using Vue CLI.
   vue create my-vue-app
   cd my-vue-app
Enter fullscreen mode Exit fullscreen mode

Then, install axios:

   npm install axios
Enter fullscreen mode Exit fullscreen mode
  1. Create Components: Create two components, UserForm.vue for the modal form and UserList.vue to display a list of users.
   <!-- UserForm.vue -->
   <template>
     <div>
       <label>Name:</label>
       <input v-model="name" />
       <button @click="handleSave">Save</button>
       <button @click="onCancel">Cancel</button>
     </div>
   </template>

   <script>
   export default {
     props: {
       onSave: Function,
       onCancel: Function,
       user: Object,
     },
     data() {
       return {
         name: this.user ? this.user.name : '',
       };
     },
     methods: {
       handleSave() {
         const newUser = { id: this.user ? this.user.id : null, name: this.name };
         this.onSave(newUser);
       },
     },
   };
   </script>
Enter fullscreen mode Exit fullscreen mode
   <!-- UserList.vue -->
   <template>
     <ul>
       <li v-for="user in users" :key="user.id">
         {{ user.name }} <button @click="onEdit(user)">Edit</button>
       </li>
     </ul>
   </template>

   <script>
   export default {
     props: {
       users: Array,
       onEdit: Function,
     },
   };
   </script>
Enter fullscreen mode Exit fullscreen mode
  1. App Component: In your App.vue or main component, manage the state, handle API calls, and render the UserForm and UserList.
   <!-- App.vue -->
   <template>
     <div>
       <h1>User Management</h1>
       <user-list :users="users" :on-edit="handleEdit" />
       <user-form :on-save="handleSave" :on-cancel="handleCancel" :user="editingUser" />
     </div>
   </template>

   <script>
   import axios from 'axios';
   import UserForm from './components/UserForm.vue';
   import UserList from './components/UserList.vue';

   const apiUrl = 'https://your-api-url.com/users'; // Replace with your actual API URL

   export default {
     components: {
       UserForm,
       UserList,
     },
     data() {
       return {
         users: [],
         editingUser: null,
       };
     },
     mounted() {
       // Fetch initial user data from the API
       axios.get(apiUrl).then((response) => {
         this.users = response.data;
       });
     },
     methods: {
       handleSave(user) {
         const method = user.id ? 'put' : 'post';
         const url = user.id ? `${apiUrl}/${user.id}` : apiUrl;

         axios[method](url, user)
           .then((response) => response.data)
           .then((savedUser) => {
             this.users = user.id
               ? this.users.map((u) => (u.id === savedUser.id ? savedUser : u))
               : [...this.users, savedUser];
             this.editingUser = null;
           });
       },
       handleEdit(user) {
         this.editingUser = user;
       },
       handleCancel() {
         this.editingUser = null;
       },
     },
   };
   </script>
Enter fullscreen mode Exit fullscreen mode

Make sure to replace 'https://your-api-url.com/users' with the actual URL of your API endpoint.

  1. Run the App: Start your Vue.js app:
   npm run serve
Enter fullscreen mode Exit fullscreen mode

This example provides a basic structure, and you may need to handle loading states, errors, and other considerations based on your application requirements. Adjust the code accordingly.

Angular

Certainly! Below is an example of implementing create and update operations with an API in Angular. We'll use Angular components, services, and the HttpClient module for making HTTP requests.

  1. Create Angular App: If you haven't already, create a new Angular app using Angular CLI.
   ng new my-angular-app
   cd my-angular-app
Enter fullscreen mode Exit fullscreen mode
  1. Generate Components: Generate two components, user-form for the modal form and user-list to display a list of users.
   ng generate component user-form
   ng generate component user-list
Enter fullscreen mode Exit fullscreen mode
  1. Create Service: Create a service to handle API calls.
   ng generate service user
Enter fullscreen mode Exit fullscreen mode

Update the user.service.ts file with the following code:

   // user.service.ts
   import { Injectable } from '@angular/core';
   import { HttpClient } from '@angular/common/http';
   import { Observable } from 'rxjs';

   const apiUrl = 'https://your-api-url.com/users'; // Replace with your actual API URL

   @Injectable({
     providedIn: 'root',
   })
   export class UserService {
     constructor(private http: HttpClient) {}

     getUsers(): Observable<any[]> {
       return this.http.get<any[]>(apiUrl);
     }

     saveUser(user: any): Observable<any> {
       const method = user.id ? 'put' : 'post';
       const url = user.id ? `${apiUrl}/${user.id}` : apiUrl;

       return this.http[method](url, user);
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Update Components: Update the generated components with the following code:
   // user-form.component.ts
   import { Component, Input, Output, EventEmitter } from '@angular/core';

   @Component({
     selector: 'app-user-form',
     templateUrl: './user-form.component.html',
     styleUrls: ['./user-form.component.css'],
   })
   export class UserFormComponent {
     @Input() user: any;
     @Output() save = new EventEmitter<any>();
     @Output() cancel = new EventEmitter<void>();

     name: string = '';

     ngOnChanges() {
       this.name = this.user ? this.user.name : '';
     }

     onSave() {
       const newUser = { id: this.user ? this.user.id : null, name: this.name };
       this.save.emit(newUser);
     }
   }
Enter fullscreen mode Exit fullscreen mode
   <!-- user-form.component.html -->
   <div>
     <label>Name:</label>
     <input [(ngModel)]="name" />
     <button (click)="onSave()">Save</button>
     <button (click)="cancel.emit()">Cancel</button>
   </div>
Enter fullscreen mode Exit fullscreen mode
   // user-list.component.ts
   import { Component, Input, Output, EventEmitter } from '@angular/core';

   @Component({
     selector: 'app-user-list',
     templateUrl: './user-list.component.html',
     styleUrls: ['./user-list.component.css'],
   })
   export class UserListComponent {
     @Input() users: any[];
     @Output() edit = new EventEmitter<any>();

     onEdit(user: any) {
       this.edit.emit(user);
     }
   }
Enter fullscreen mode Exit fullscreen mode
   <!-- user-list.component.html -->
   <ul>
     <li *ngFor="let user of users">
       {{ user.name }} <button (click)="onEdit(user)">Edit</button>
     </li>
   </ul>
Enter fullscreen mode Exit fullscreen mode
  1. Update App Component: Update the app.component.ts file with the following code:
   // app.component.ts
   import { Component, OnInit } from '@angular/core';
   import { UserService } from './user.service';

   @Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css'],
   })
   export class AppComponent implements OnInit {
     users: any[];
     editingUser: any;

     constructor(private userService: UserService) {}

     ngOnInit() {
       // Fetch initial user data from the API
       this.userService.getUsers().subscribe((data) => {
         this.users = data;
       });
     }

     handleSave(user: any) {
       this.userService.saveUser(user).subscribe((savedUser) => {
         this.users = user.id
           ? this.users.map((u) => (u.id === savedUser.id ? savedUser : u))
           : [...this.users, savedUser];
         this.editingUser = null;
       });
     }

     handleEdit(user: any) {
       this.editingUser = user;
     }

     handleCancel() {
       this.editingUser = null;
     }
   }
Enter fullscreen mode Exit fullscreen mode

Update the app.component.html file to include the app components:

   <!-- app.component.html -->
   <div>
     <h1>User Management</h1>
     <app-user-list [users]="users" (edit)="handleEdit($event)"></app-user-list>
     <app-user-form
       [user]="editingUser"
       (save)="handleSave($event)"
       (cancel)="handleCancel()"
     ></app-user-form>
   </div>
Enter fullscreen mode Exit fullscreen mode
  1. Update AppModule: Make sure to import the necessary modules and add the components to the declarations array in app.module.ts.
   // app.module.ts
   import { BrowserModule } from '@angular/platform-browser';
   import { NgModule } from '@angular/core';
   import { FormsModule } from '@angular/forms';
   import { HttpClientModule } from '@angular/common/http';
   import { AppComponent } from './app.component';
   import { UserFormComponent } from './user-form/user-form.component';
   import { UserListComponent } from './user-list/user-list.component';
   import { UserService } from './user.service';

   @NgModule({
     declarations: [AppComponent, UserFormComponent, UserListComponent],
     imports: [BrowserModule, FormsModule, HttpClientModule],
     providers: [UserService],
     bootstrap: [AppComponent],
   })
   export class AppModule {}
Enter fullscreen mode Exit fullscreen mode
  1. Run the App: Start your Angular app:
   ng serve
Enter fullscreen mode Exit fullscreen mode

Navigate to http://localhost:4200/ in your browser. This example provides a basic structure, and you may need to handle loading states, errors, and other considerations based on your application requirements. Adjust the code accordingly.

Top comments (0)