zenith707's avatar

Tracking state of checkboxes with Inertia React

Can anyone spot why the checked value is not updating on click. The data is passing in an object with one key 'genre' which features array of id's from the controller and those checkboxes are being checked as expected. But they do not update i.e. they cannot revert to true or false and change the checked state.

const { data, setData, post, put, processing, errors } = useForm({
        genres: [],
    });

    const genreIds = user.genres.map((genre) => genre.id);

    const onHandleChange = (event) => {
        let id = e.target.value;

        if (e.target.checked) {
            setData("genres", [...data.genres, id]);
        } else {
            setData(
                "genres",
                data.genres.filter((item) => item !== id)
            );
        }
    };

{genres.map((genre, index) => {
<Checkbox
    id={genre.id}
    name={genre.name}
    value={genre.id}
    checked={genreIds.includes(
        genre.id
    )}
    handleChange={onHandleChange}
/>               		

Checkbox component:

export default function Checkbox({
    id,
    name,
    value,
    handleChange,
    checked,
    required,
}) {
    return (
        <input
            id={id}
            type="checkbox"
            name={name}
            value={value}
            className="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
            onChange={(e) => handleChange(e)}
            required={required}
            checked={checked}
        />
    );
}

0 likes
1 reply
Artemis-'s avatar

It looks like the checked state is set by the variable genreIds. However, I cannot see if that variable is being properly updated with the new values once setData happens. I do not see a user variable anywhere. Maybe genreIds should be this?

const genreIds = data.genres.map((genre) => genre.id);

Please or to participate in this conversation.