I am working on a simple form that submits some data to the server. And there is a field where I have to add more than an input and store them in an array named "users". What I mean is, I want to have checkboxes and whenever I check a box, it adds its value to the array that is named users. I am using this function to get values from the form and connect it to redux :
export function setFormValue(field) {
return function (dispatch) {
dispatch({ type: types.SET_FORM_VALUE, payload: field })
};
}
Here is how my checkboxes are set in the form:
<FormGroup check>
<Label check>
<Input type="checkbox" onChange={setFormValue} value={form.users} />
David
</Label>
</FormGroup>
<FormGroup check>
<Label check>
<Input type="checkbox" onChange={setFormValue} value={form.users} />
Marco
</Label>
</FormGroup>
<FormGroup check>
<Label check>
<Input type="checkbox" onChange={setFormValue} value={form.users} />
Leen
</Label>
</FormGroup>
And here is how I am handling my form so that it will looks like :
form : {
somedata : somedata,
createAdress: {some data inside the object},
users: []
}
And here is how I handle the state in the reducer :
import * as types from './actionTypes';
const initialState = {
fetchedData: [
{}
],
branchWithID: {},
form: {
createAddress: {},
users: []
}
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case types.LOAD_DATA_SUCCESS:
return {
...state,
fetchedData: action.payload
}
case types.LOAD_BRANCH_WITH_ID_SUCCESS:
return {
...state,
branchWithID: action.payload
}
case types.SET_FORM_VALUE:
let form = action.payload
form.users = form.users || [];
const createAddress = [
"nickname",
"building_name",
"office_number",
"zone_number",
"street_number",
"building_number",
"ciy",
"area",
"pin_link",
"pin-lat",
"pin-lng",
"company",
"customer"
];
if (createAddress.includes(action.payload.target.name)) {
return {
...state,
form: {
...state.form,
createAddress: {
...state.form.createAddress,
[action.payload.target.name]: action.payload.target.value
}
}
};
}
return {
...state,
form: {
...state.form,
[action.payload.target.name]: action.payload.target.value
}
};
default:
return state;
}
}
So now what I want is to take many inputs from the form and store them in the array of users. How can I achieve this?
Here is a link to my project on codesandbox : https://codesandbox.io/s/silly-tree-eqb2n?file=/src/App.js
form.usersproperty?