1

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>

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

3 Comments

so how do i handle defaultChecked? i updated question with information on the toggle switch defaultChecked
i tried this by adding new const to handle the value and it did not work const toSwitch = (val) => val === false ? "disabled" : "enabled"; and then changed defaultChecked={el.status} to defaultChecked={toSwitch(el.status)} but did not work
ok fixed with const toSwitch = (val) => val === "enabled" ? true : false; and then changed defaultChecked={el.status} to defaultChecked={toSwitch(el.status)}...works now..thanks!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.