Advertisement
ikamal7

withForm.js

Jun 7th, 2023
897
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState } from 'react';
  2. import { useDispatch, useSelector } from 'react-redux';
  3. import { updateField } from '@/redux/form.slice';
  4.  
  5.  
  6. const withForm = (WrappedComponent) => {
  7.     const FormComponent = (props) => {
  8.         const dispatch = useDispatch();
  9.         const formFields = useSelector((state) => state.form.fields);
  10.         const [fields, setFields] = useState(formFields);
  11.  
  12.         const handleFieldChange = (fieldId, value) => {
  13.             const updatedFields = fields.map((field) => {
  14.                 if (field.id === fieldId) {
  15.                     return { ...field, value };
  16.                 }
  17.                 return field;
  18.             });
  19.             setFields(updatedFields);
  20.             dispatch(updateField({ fieldId, value }));
  21.         };
  22.  
  23.         return (
  24.             <WrappedComponent
  25.                 {...props}
  26.                 fields={fields}
  27.                 setFields={setFields}
  28.                 handleFieldChange={handleFieldChange}
  29.             />
  30.         );
  31.     };
  32.  
  33.     return FormComponent;
  34. };
  35.  
  36. export default withForm;
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement