Reputation: 4349
I am able to set state fine with data map using react hooks when i am using boolean values
I have a switch button that toggles from enabled to disabled
so status
can be true or false...when enabled status == true
and when disabled status == false
works fine below
setData(data => data.map(el => el.id === postid
? { ...el, status: !el.status }
: el
));
but now i want to use a string so status
will now be using enabled
or disabled
values as opposed to boolean of true or false
so when el.status == disabled
then status == enabled
and when el.status == enabled
then status == disabled
what do i do to accomplish same thing from above code?
UPDATE:
here is how i currently get the value of defaultChecked
for use with the toggle switch
<label className="switch">
<input type="checkbox" defaultChecked={el.status} onClick={() => updatePost(el.id, k)} />
<span className="slider round"> </span>
</label>
Upvotes: 1
Views: 499
Reputation: 38209
You can add some simple helper function which converts to string status:
const toStatus = (val) => val === true ? "enabled" : "disabled";
And then converting becomes simpler. Let me show an example:
let arr = [
{id: 1, status: false},
{id: 2, status: true},
{id: 3, status: false},
]
const toStatus = (val) => val === true ? "enabled" : "disabled";
const withStringValues = arr.map(item => ({ ...item, status: toStatus(item.status) }))
console.log(withStringValues)
then add a new constant to track defaultChecked
value by converting string
back to boolean
const toSwitch = (val) => val === "enabled" ? true : false;
and then update toggle switch to this
<label className="switch">
<input type="checkbox" defaultChecked={toSwitch(el.status)} onClick={() => updatePost(el.id, k)} />
<span className="slider round"> </span>
</label>
Upvotes: 1