'React-typescript, looping over the state in reducer function
How can I loop over the whole useReducer state and set the its "isWrong" property to true if there is no value after form submission. What is the best approach to solve that. Because the problem is that I could loop over the state and make the separate variable but the problem is I need the "isWrong" property set inside state because it makes fields color red when it is wrong.
state = const initialStateReducer: inputsFormState = {
title: {
val: "",
isValid: false,
isClicked: false,
isWrong: false,
},
description: {
val: "",
isValid: false,
isClicked: false,
isWrong: false,
},}
reducer:
const inputReducer = (
state: inputsFormState,
action: inputsFormAction
): inputsFormState => {
let isValid = false;
let isClicked = true;
let isWrong = false;
const { content } = action;
const validateInput = (content: string) => {
isClicked = true;
isValid = content.length > 0;
isWrong = isClicked && !isValid;
};
if (
action.type === ActionKind.stringVal &&
action.field &&
typeof content === "string"
) {
validateInput(content);
return {
...state,
[action.field]: {
val: content,
isValid: isValid,
isClicked: isClicked,
isWrong: isWrong,
},
};
}
Form submission
const onSubmitHandler = (e: React.FormEvent): void => {
e.preventDefault();
if (formIsValid && user?.displayName) {
const recipe: Recipe = {
username: user.displayName,
title: inputsValues.description.val,
type: type,
description: inputsValues.title.val,
id: Math.random(),
time: time,
ingredients: ingredients,
stars: Math.floor(Math.random() * 6) + 1,
steps: steps,
comments: [],
};
dispatch(recipeAction.addRecipe(recipe));
dispatch(sendData(recipe));
navigate("/");
}
};
Solution 1:[1]
You can change your validateInput arrow function to augment the state as follows:
const validateInput = (state: inputsFormState, content: string): inputsFormState => {
Object.keys(state).forEach((stateKey) => {
validatedState[stateKey] = {
isClicked: true,
isValid: content.length > 0,
isWrong: isClicked && !isValid,
val: state[stateKey].val,
};
});
};
Then you can use it as follows:
validateInput(state, content);
return { ...state };
Also, if you want want content to be set in all of the val properties, you can change val: state[stateKey].val to val: content.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ovidijus Parsiunas |
