Home > Net >  Flatlist with multiple checkbox React Native
Flatlist with multiple checkbox React Native

Time:02-10

I am using flatlist with checkboxes and I want to save the data of selected item into an array but can't be able to save the data in array

my json response

{
 "tS_CT_CODE": "ELC",
 "tS_TASK_CODE": "ELC001",
 "tS_TITLE": "Light Problem",
 "tS_TITLE_AR": "",
 "tS_PRICE": 100.0,
 "tS_STATUS": "A",
 "tS_USER_ID": "",
 "tS_SYSTEM_DATE": ""
}

I want to save tsPrice in different array and tsTitle in different array I am just able to do save only ts_title in taskName as you can see below how can I save ts_price in different array?

here is my CheckBox

const [toggleCheckBox, setToggleCheckBox] = useState([]);

<CheckBox
  checked={toggleCheckBox.includes(item.tS_TITLE)}
  onPress={() => handleListTap(item)}
/>

const handleListTap = async item => {
  const taskName = [...toggleCheckBox];
  const index = taskName.indexOf(item.tS_TITLE);
   if (index > -1) {
     taskName.splice(index, 1);
   } else {
     taskName.push(item.tS_TITLE);
   }
  console.log(taskName);
  setToggleCheckBox(taskName);
  // navigation.navigate('MaintenanceTimeSlot');
};

CodePudding user response:

From above code I am assuming that your are passing an array with JSON response object mentioned above to a Flatlist component and CheckBox is Flatlist's child component. So in that case you can create another array for prices like shown below

...
const [toggleCheckBox, setToggleCheckBox] = useState([]);
const [priceArray, setPriceArray] = useState([]);   // add this
...
<CheckBox
  checked={toggleCheckBox.includes(item.tS_TITLE)}
  onPress={() => handleListTap(item)}
/>
...
const handleListTap = async item => {
  let taskName = [...toggleCheckBox];
  let taskPrice = [...priceArray];    // add this
  const index = taskName.indexOf(item.tS_TITLE);
   if (index > -1) {
     taskName.splice(index, 1);
     taskPrice.splice(index, 1);     // add this
   } else {
     taskName.push(item.tS_TITLE);
     taskPrice.push(item.tS_TITLE);  // add this
   }
  console.log(taskName, taskPrice);
  setToggleCheckBox(taskName);
  setPriceArray(taskPrice);          // add this
  // navigation.navigate('MaintenanceTimeSlot');
};
...
  • Related