I am using useState in react native.
I created a state called lstandtime and lacttime.
I also created functions called onSubmitfunc and LsonChangefunc and LaconChangefunc.
We need 3 components called MainCons, so we made 3 components. But it could be three or more.
As you can see, the format of each component, state, and function are all similar, but three are needed, so a number is attached to the end of the variable.
I want to reduce duplicate code, but how do I do it?
this is my code
function Component() {
const [lstandtime1, setLstandtime1] = useState("");
const [lacttime1, setLacttime1] = useState("");
const [lstandtime2, setLstandtime2] = useState("");
const [lacttime2, setLacttime2] = useState("");
const [lstandtime3, setLstandtime3] = useState("");
const [lacttime3, setLacttime3] = useState("");
const onSubmitfunc1 = useCallback(
(e) => {
e.preventDefault();
},
[lstandtime1, lacttime1],
);
const LsonChangefunc1 = useCallback((e) => {
e.preventDefault();
setLstandtime1(e.target.value);
}, []);
const LaconChangefunc1 = useCallback((e) => {
e.preventDefault();
setLacttime1(e.target.value);
}, []);
const onSubmitfunc2 = useCallback(
(e) => {
e.preventDefault();
},
[lstandtime2, lacttime2],
);
const LsonChangefunc2 = useCallback((e) => {
e.preventDefault();
setLstandtime2(e.target.value);
}, []);
const LaconChangefunc2 = useCallback((e) => {
e.preventDefault();
setLacttime2(e.target.value);
}, []);
const onSubmitfunc3 = useCallback(
(e) => {
e.preventDefault();
},
[lstandtime3, lacttime3],
);
const LsonChangefunc3 = useCallback((e) => {
e.preventDefault();
setLstandtime3(e.target.value);
}, []);
const LaconChangefunc3 = useCallback((e) => {
e.preventDefault();
setLacttime3(e.target.value);
}, []);
return (
<>
<MainCons onClick={onSubmitfunc1}>
<input value={lstandtime1} onChange={LsonChangefunc1} />
<input value={lacttime1} onChange={LaconChangefunc1} />
</MainCons>
<MainCons onClick={onSubmitfunc2}>
<input value={lstandtime2} onChange={LsonChangefunc2} />
<input value={lacttime2} onChange={LaconChangefunc2} />
</MainCons>
<MainCons onClick={onSubmitfunc3}>
<input value={lstandtime3} onChange={LsonChangefunc3} />
<input value={lacttime3} onChange={LaconChangefunc3} />
</MainCons>
</>
);
}
3
Answers
Maybe declare an object with all these properties and then use them as parameters at your update functions.
See my example code below. This is just a snippet to give you the idea.
If you need more than these and you want to go further, you could create a loop
and then parametrize your
MainCons
component with these values usingObject.entries
Edit
Cannot test my code but I thought about AKX’s comment and i wrote this solution. It’s cleaner and I hope it helps you
If you have multiple states of the same kind you could use an array as mentioned by @AKX in the comments: