How to implement create & update details in React, Vue & Angular?
Published: 2024-02-27 15:31:18

### 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.

   ```bash
   npx create-react-app my-react-app
   cd my-react-app
   ```

2. **Create Components:**
   Create two components, `UserForm.js` for the modal form, and `UserList.js` to display a list of users.

   ```jsx
   // 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;
   ```

   ```jsx
   // 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;
   ```

3. **App Component:**
   In your `App.js` or main component, manage the state, handle API calls, and render the `UserForm` and `UserList`.

   ```jsx
   // 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;
   ```

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

4. **Run the App:**
   Start your React app:

   ```bash
   npm start
   ```

   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.

   ```bash
   vue create my-vue-app
   cd my-vue-app
   ```

   Then, install `axios`:

   ```bash
   npm install axios
   ```

2. **Create Components:**
   Create two components, `UserForm.vue` for the modal form and `UserList.vue` to display a list of users.

   ```html
   <!-- 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>
   ```

   ```html
   <!-- 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>
   ```

3. **App Component:**
   In your `App.vue` or main component, manage the state, handle API calls, and render the `UserForm` and `UserList`.

   ```html
   <!-- 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>
   ```

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

4. **Run the App:**
   Start your Vue.js app:

   ```bash
   npm run serve
   ```

   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.

   ```bash
   ng new my-angular-app
   cd my-angular-app
   ```

2. **Generate Components:**
   Generate two components, `user-form` for the modal form and `user-list` to display a list of users.

   ```bash
   ng generate component user-form
   ng generate component user-list
   ```

3. **Create Service:**
   Create a service to handle API calls.

   ```bash
   ng generate service user
   ```

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

   ```typescript
   // 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);
     }
   }
   ```

4. **Update Components:**
   Update the generated components with the following code:

   ```typescript
   // 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);
     }
   }
   ```

   ```html
   <!-- user-form.component.html -->
   <div>
     <label>Name:</label>
     <input [(ngModel)]="name" />
     <button (click)="onSave()">Save</button>
     <button (click)="cancel.emit()">Cancel</button>
   </div>
   ```

   ```typescript
   // 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);
     }
   }
   ```

   ```html
   <!-- user-list.component.html -->
   <ul>
     <li *ngFor="let user of users">
       {{ user.name }} <button (click)="onEdit(user)">Edit</button>
     </li>
   </ul>
   ```

5. **Update App Component:**
   Update the `app.component.ts` file with the following code:

   ```typescript
   // 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;
     }
   }
   ```

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

   ```html
   <!-- 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>
   ```

6. **Update AppModule:**
   Make sure to import the necessary modules and add the components to the `declarations` array in `app.module.ts`.

   ```typescript
   // 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 {}
   ```

7. **Run the App:**
   Start your Angular app:

   ```bash
   ng serve
   ```

   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.