All files / hooks useKiwtFieldArray.js

3.7% Statements 1/27
0% Branches 0/12
0% Functions 0/9
3.84% Lines 1/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64      27x                                                                                                                        
import { useEffect, useState } from 'react';
import { useFieldArray } from 'react-final-form-arrays';
 
const useKiwtFieldArray = (name, submitWholeDeletedObject = false) => {
  const { fields } = useFieldArray(name);
  const { value: values = [] } = fields;
  const [endOfList, setEndOfList] = useState(0);
 
  useEffect(() => {
    const i = values.filter(line => !line._delete);
    setEndOfList(i.length);
  }, [values]);
 
  const onAddField = (field = { _delete: false }) => {
    fields.insert(endOfList, field);
  };
 
  const onMarkForDeletion = (field) => {
    if (field && field.id) {
      if (submitWholeDeletedObject) {
        fields.push({ ...field, _delete: true });
      } else {
        fields.push({ id: field.id, _delete: true });
      }
    }
  };
 
  const onDeleteField = (index, field) => {
    fields.remove(index);
    onMarkForDeletion(field);
  };
 
  const onPrependField = (field = { _delete: false }) => {
    fields.unshift(field);
  };
 
  const onReplaceField = (index, field) => {
    if (fields.update) { // react-final-form-arrays
      fields.update(index, field);
    }
  };
 
  const onUpdateField = (index, field) => {
    fields.update(index, {
      ...fields.value[index],
      ...field,
    });
  };
 
  const items = values.slice(0, endOfList);
 
  return {
    items,
    onAddField,
    onDeleteField,
    onMarkForDeletion,
    onPrependField,
    onReplaceField,
    onUpdateField,
  };
};
 
export default useKiwtFieldArray;