mercredi 20 avril 2022

How to populate unchecked checkboxes for edit page in React

I have an edit page of a recipe that is populated correctly using findOne axios call and populates all of the information for that recipe. However, it only displays the checkboxes that are checked and not the checkbox objects that are unchecked. I want it to display all checkboxes, both checked and unchecked. See below code.

Edit.jsx

const Edit = (props) => {

    const { _id } = useParams({})
    const [form, setForm] = useState({
        title: "",
        description: "",
        tags: [
            { name: "Athletic/Higher caloric", isChecked: false },
            { name: "Aggressive Weight Loss", isChecked: false },
            { name: "Kid-Friendly", isChecked: false },
            { name: "Non-Vegan", isChecked: false },
            { name: "Diabetes reversal", isChecked: false },
            { name: "Quick and Easy", isChecked: false },
        ],
    })

    useEffect(() => {
        axios.get(`http://localhost:8000/api/recipes/${_id}`)
            .then(res => {
                console.log(res.data.results);
                setForm(res.data.results);
            })
            .catch(err => {
                console.log(err)
                setErrors(err)
            })
    }, [_id])


My checkedHandler from create page:

const handleCheckedTags = (index) => {
        setForm(prev => ({
            ...prev,
            tags: [
                ...prev?.tags?.map(
                    ({ isChecked, ...rest }, idx) => (
                        idx === index ?
                            { ...rest, isChecked: !isChecked } :
                            { ...rest, isChecked })
                )]
        }));
    }

And here is my return code (the edit form):

return (
  <form>
       {
        form.tags.map((tag, i) => (
          <div className="form-inline mx-3" key={i}>
              <input
                   type="checkbox"
                   value={tag.name}
                   checked={tag.isChecked}
                   onChange={(event) => handleCheckedTags(i)}
                   key={i}
                 />
             </div>
           ))}
   </div>
   <input type="submit" />
 </form>

I know I have a single form state to begin with, which was how I setup my create form. Should I have set it up differently or is there a way to make sure the unchecked checkboxes display for the edit page?

Thanks in advance for your help.




Aucun commentaire:

Enregistrer un commentaire