Crudmockapi
Crudmockapi
component and integrate it with MockAPI to handle CRUD operations, we'll follow these
steps:
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 });
});
};
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>
<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>
);
}
}
Key Features:
MockAPI URL:
● Replace the URL
(https://6359c57e33b2e8a83b7de9a0.mockapi.io/users) with your
MockAPI project URL.
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.