0% found this document useful (0 votes)
3 views7 pages

Crudmockapi

The document outlines the steps to convert a Formik-based functional component into a class-based React component that integrates with MockAPI for CRUD operations. Key features include form handling with Formik, validation, and methods for adding, updating, and deleting users. The component fetches users on mount and updates the UI in real-time based on API interactions.

Uploaded by

kkannake964
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Crudmockapi

The document outlines the steps to convert a Formik-based functional component into a class-based React component that integrates with MockAPI for CRUD operations. Key features include form handling with Formik, validation, and methods for adding, updating, and deleting users. The component fetches users on mount and updates the UI in real-time based on API interactions.

Uploaded by

kkannake964
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

To convert the Formik-based form from your functional component to a class-based React

component and integrate it with MockAPI to handle CRUD operations, we'll follow these
steps:

1. Create the Class Component: Convert the functional component to a class-based


one.
2. Integrate Formik: We’ll use Formik in the class component and handle form state
manually through the class’s state.
3. Handle CRUD Operations: Use fetch to interact with MockAPI for Create, Read,
Update, and Delete operations.

Let's start with converting the form to a class-based component:

Full Code for Class-Based Component with Formik and MockAPI


Integration
javascript
Copy code
import React, { Component } from 'react';
import { Formik } from 'formik';

class CrudForm extends Component {


constructor(props) {
super(props);
this.state = {
users: [], // Store users
editId: null, // To track which user is being edited
};
}

// Fetch users from MockAPI


fetchUsers = () => {
fetch('https://6359c57e33b2e8a83b7de9a0.mockapi.io/users')
.then(response => response.json())
.then(users => this.setState({ users }));
};

// Add new user to MockAPI


addUser = (values, { setSubmitting, resetForm }) => {
const newUser = { email: values.email, password: values.password
};
fetch('https://6359c57e33b2e8a83b7de9a0.mockapi.io/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newUser),
})
.then(response => response.json())
.then((addedUser) => {
this.setState(prevState => ({
users: [...prevState.users, addedUser],
}));
resetForm(); // Reset form after submission
setSubmitting(false);
});
};

// Update user in MockAPI


updateUser = (values, { setSubmitting, resetForm }) => {
const updatedUser = { email: values.email, password:
values.password };

fetch(`https://6359c57e33b2e8a83b7de9a0.mockapi.io/users/${this.stat
e.editId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updatedUser),
})
.then(response => response.json())
.then((updatedUser) => {
const updatedUsers = this.state.users.map(user =>
user.id === this.state.editId ? updatedUser : user
);
this.setState({
users: updatedUsers,
editId: null,
});
resetForm(); // Reset form after submission
setSubmitting(false);
});
};
// Delete user from MockAPI
deleteUser = (id) => {
fetch(`https://6359c57e33b2e8a83b7de9a0.mockapi.io/users/${id}`,
{
method: 'DELETE',
})
.then(() => {
const filteredUsers = this.state.users.filter(user =>
user.id !== id);
this.setState({ users: filteredUsers });
});
};

// Triggered when the form is submitted


handleSubmit = (values, { setSubmitting, resetForm }) => {
if (this.state.editId === null) {
this.addUser(values, { setSubmitting, resetForm });
} else {
this.updateUser(values, { setSubmitting, resetForm });
}
};

// Edit a user (pre-fill form for editing)


editUser = (user) => {
this.setState({
editId: user.id,
});
};

// Fetch users when the component mounts


componentDidMount() {
this.fetchUsers();
}

render() {
return (
<div>
<h1>CRUD Form with Formik in Class Component</h1>

<Formik
initialValues={{ email: '', password: '' }}
validate={values => {
const errors = {};
if (!values.email) {
errors.email = 'Required';
} else if (

!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
) {
errors.email = 'Invalid email address';
}
if (!values.password) {
errors.password = 'Required';
}
return errors;
}}
onSubmit={this.handleSubmit}
>
{({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
resetForm,
}) => (
<form onSubmit={handleSubmit}>
<div>
<input
type="email"
name="email"
onChange={handleChange}
onBlur={handleBlur}
value={values.email}
placeholder="Email"
/>
{errors.email && touched.email &&
<div>{errors.email}</div>}
</div>
<div>
<input
type="password"
name="password"
onChange={handleChange}
onBlur={handleBlur}
value={values.password}
placeholder="Password"
/>
{errors.password && touched.password &&
<div>{errors.password}</div>}
</div>

<button type="submit" disabled={isSubmitting}>


{this.state.editId === null ? 'Add User' : 'Update
User'}
</button>
</form>
)}
</Formik>

<h2>User List</h2>
<table>
<thead>
<tr>
<th>Email</th>
<th>Password</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{this.state.users.map(user => (
<tr key={user.id}>
<td>{user.email}</td>
<td>{user.password}</td>
<td>
<button onClick={() =>
this.editUser(user)}>Edit</button>
<button onClick={() =>
this.deleteUser(user.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}

export default CrudForm;

Key Features:

1. Formik for Form Handling:


○ Formik handles form state (email and password) in the class-based
component. We pass initialValues, validate, and onSubmit to the
Formik component.
2. Validation:
○ The form is validated by checking if the email field is not empty and if it
matches a valid email pattern. Similarly, we check that password is not
empty.
3. Handle Add and Update Logic:
○ The handleSubmit method checks if we are in "Add" or "Edit" mode based
on whether editId is null. If editId is not null, it triggers an update API
call; otherwise, it performs a create operation.
4. CRUD Operations:
○ Create: When the form is submitted in add mode, the user is added to
MockAPI using a POST request.
○ Read: On initial render, users are fetched from MockAPI using a GET request.
○ Update: When editing a user, the form is populated with the existing data,
and after submission, the PUT request updates the user on MockAPI.
Delete: Clicking the "Delete" button removes the user using a DELETE

request.
5. Handling Edit Mode:
○ When you click the "Edit" button for a user, the form is populated with their
email and password, and the submit button text changes to "Update User".
6. Component Lifecycle:
○ The componentDidMount method is used to fetch users from MockAPI
when the component is first loaded.

MockAPI URL:
● Replace the URL
(https://6359c57e33b2e8a83b7de9a0.mockapi.io/users) with your
MockAPI project URL.

Run the App:

1. Set up the API: Create a users resource in MockAPI.


2. Update the URL: Ensure that the fetch URLs in your code match the MockAPI
URLs.
3. Start the App: Run your React app with npm start or yarn start.

Conclusion:

This is a complete class-based CRUD app using Formik for form handling and integrated
with MockAPI for backend operations. It supports Create, Read, Update, and Delete
functionality with real-time updates from the API.

You might also like