Forge App - Persist Checkbox State

Hey folks,

I am trying to build a Forge app, and have a problem trying to persist the state of checkboxes in an issue and display the selected checkboxes as checked when a user returns to the issue later.

Here is what I am doing:

  1. Render checklist
    
  2. Select one or more checkboxes
    
  3. Persist the checkbox ids using the property api
    

On return to the issue,

  1. Using a useEffect hook, retrieve the checkbox ids using the property api and set the checkboxes in the list that match the stored checkbox ids.

I confirmed the values are stored and retrieved, but the checkboxes don’t render as checked. I am confused as to how I am supposed to set the checkboxlist array items that I am passing in so that certain checkboxes are checked.

<Form onSubmit={handleOnSubmit}>
    <Checkboxes {...checkboxlist} />
</Form>

I see in the documentation that there is a checkbox property defaultChecked which is a boolean, so I assume the following would work.

useEffect(async() => {
    //gets an array of int that represents the checkbox ids that are selected
    const values = await getProperty()

    //if values are defined, loop through the checkboxes to find those
    //that match the selected values and set defaultChecked true
    if (values) {
        checkboxlist.checkboxes.map((checkbox, idx) => {
            values.map((value, idx) => {
                if (checkbox.id == value)
                    checkbox.defaultChecked = true
            })
        })

        //update the checkbox list in state so we can re-render
        setCheckboxList(checkboxlist)
    }
}, [])

It’s been some time since I have done React work, so it is entirely possible I have brain-farted something, but if anyone could please point me in the right direction, I’d appreciate it.

Woot! Got it. I think the above is correct, but as I loop through creation of my checkboxes, I needed the defaultChecked property. It didn’t make sense to me because the property name included “default”.

export function Checkboxes({checkboxes, setCheckbox}) {
    const checkboxlist = checkboxes.map((checkbox, i) => {
        return (
         <Checkbox
             name={"checkbox"+checkbox.id.toString()}
             key={"checkbox"+checkbox.id.toString()}
             type="checkbox"
             defaultChecked={checkbox.defaultChecked}      <<<=== This was the issue
             label={checkbox.question}
             value={checkbox.id}
         />
    )})

    return (
        <CheckboxGroup
            label="Questions"
            name="checkbox_group">
            {checkboxlist}
        </CheckboxGroup>
    )
}
3 Likes