I'm just learning Redux and I have a question about more slices.
I have a form that consists of several modules (multi-step form). One slice helps me store the state of the input value. And the second I want to use to validate inputs using regex. This validation will be checked after click on the next button.
The question is probably a matter of convention. Use 2 files e.g. inputSlice.js and isValidSlice.js
Or use combineReducers in one inputSlice file instead?
My current slice for storing value input
import { createSlice } from "@reduxjs/toolkit";
export const inputDataSlice = createSlice({
name: "inputData",
initialState: {
firstName: null,
lastName: null,
email: null,
phone: null,
},
reducers: {
setInputData: (state, action) => {
const data = action.payload;
switch (data.id) {
case "firstName":
return void (state.firstName = data.value);
case "lastName":
return void (state.lastName = data.value);
case "email":
return void (state.email = data.value);
case "phone":
return void (state.phone = data.value);
default:
return;
}
},
},
});
export const { setInputData } = inputDataSlice.actions;
export default inputDataSlice.reducer;
Thank You!
I prefer using one state slice to hold the user inputs and validation result of the form. Because the context of the form data entered by the user and the validation result of the form data is the form.
Since you are using RTK, updating complex state data is easy. Because RTK uses immer, Immer simplifies handling immutable data structures. Which means you don't need to use Object.assign() or Spread syntax (...) to return a shallow
copy for each level of the nested data structure.
The state slice will be like:
import { createSlice } from '@reduxjs/toolkit';
export const formSlice = createSlice({
name: 'formData',
initialState: {
formData: {
firstName: null,
lastName: null,
email: null,
phone: null,
},
validationResult: {
errors: [],
},
},
reducers: {
setFormData: (state, action) => {
const data = action.payload;
switch (data.id) {
case 'firstName':
return void (state.formData.firstName = data.value);
case 'lastName':
return void (state.formData.lastName = data.value);
case 'email':
return void (state.formData.email = data.value);
case 'phone':
return void (state.formData.phone = data.value);
default:
return;
}
},
setValidationResult: (state, action) => {
state.validationResult.errors = action.payload;
},
},
});
export const { setFormData } = formSlice.actions;
export default formSlice.reducer;