I am having a trouble where an array of Objects are returning [Object object]. What could be the missing fix to get the value of product from the mapped targeted values.
this is my sample array.
const product = [{food:'BREAD',price: 6}]
this is where I map the values and get the targeted value.
<Form >
{product.map((item, index) => (
<div key={index} className="mb-3">
<Form.Check
input value={[item]}
id={[item.food]}
type="checkbox"
label={`${item.food}`}
onClick={handleChangeCheckbox('PRODUCTS')}
/>
</div>
))}
</Form>
this handles the e.target.value
from checked checkboxes.
const handleChangeCheckbox = input => event => {
var value = event.target.value;
var isChecked = event.target.checked;
setChecked(current =>
current.map(obj => {
if (obj.option === input) {
if(isChecked){
return {...obj, chosen: [...obj.chosen, value ] };
}else{
var newArr = obj.chosen;
var index = newArr.indexOf(event.target.value);
newArr.splice(index, 1); // 2nd parameter means remove one item only
return {...obj, chosen: newArr};
}
}
return obj;
}),
);
console.log(checked);
}
finally, this is where I am having problems. Chosen is returning [Object object]console.log(checked).
const [checked, setChecked] = useState([
{ option: 'PRODUCTS',
chosen: [],
}
]);
What do I insert inside chosen:[]
to read the following arrays. Im expecting to see
0:
food: 'bread'
price: '6'
Thank you so much for helping me!
2
Answers
Hmm, don’t you need to inline your handleChangeCheckbox function? As otherwise it’s just getting executed. So instead
onClick={handleChangeCheckbox('PRODUCTS')}
doonClick={(event) => handleChangeCheckbox('PRODUCTS', event)}
.Then your handleChangeCheckbox function will start handleChangeCheckbox = (input, event) => {…}
Html input value prop is a string, and it’s change event target value is also string.
Here you are passing an object to the value prop, which will be stringified as
[Object object]
.Instead, update your change handler to take
item
instead ofevent
.Then update your input element onChange handler, to call your handler with the item itself, instead of the event.
I don’t know what the props for your component
Form.Check
are. But, I would expect aninput type="checkbox"
to have achecked
prop.A checkbox is
checked
if the item is in thechosen
state array.