Lets say I want to update my state from my hook
I would use
setStateHook(myvar)
Now If I want to customise it a bit more, I can use this
setStateHook((prevState) => { return {...prevState, myValue}}
Now the problem is that I want to customise and automate a piece of setInputFields function in my hook, but still call it the same as normal setState
My hook
export const useForm = <T extends string | number | symbol>(
initialInputData: Record<T, IDynamicFormInput>,
locale?: string
) => {
//...
const [inputFields, setInputFields] = useState<Record<T, IDynamicFormInput>>(
() => getInitialInputFields(initialInputData)
);
//AutomateSetInputFields
const setUpdateInputFields = (
value: SetStateAction<Record<T, IDynamicFormInput>>,
autoUpdate?: boolean
): void => {
if (!autoUpdate) {
setInputFields(value);
} else {
//What now? value is either S or (value: S) => void
//Argument of type '(prevState: Record<T, IDynamicFormInput>) => {}' is not assignable to parameter of type 'SetStateAction<Record<T, IDynamicFormInput>>'.
//I need to put the modified value inside setInputFields
setInputFields( ( prevState ) => {
//Everything has wrong type below
const newInputFields = { ...value };
Object.keys(newInputFields).forEach((key) => {
//Do things here
//newinputFields[key].c = "test"
})
return newInputFields;
});
}
};
//Return data so I can use it in my components
return {
inputFields,
setInputFields: setUpdateInputFields,
resetFields,
setInputField,
} as const;
//...
Usage:
setUpdateInputFields(myVar, true) //Should work if normal object
setUpdateInputFields((prevState) => { return {...prevState}}, true) //Breaks since I don't know how to process a function
//example input and output:
const obj = {
a: {
aa: 1
ab: 2
}
b: {
ba: 2
bb: 3
}
}
setUpdateInputFields((prevState) => { return {...prevState, obj}}, true)
//Output
{
a: {
num1: 1
mum2: 2
res: 3 //added
}
b: {
num1: 2
num2: 3
res: 5 //added
}
}
How can I use my function as same as useState, modify the incoming data, and call setState?