I am new to react and hooks and I am trying to set the disabled state in the below code on the condition if state.items.length is greater than 3 but I am not getting the updated values in my state object. So I tried to set the disabled state in the useEffect hook where I get the latest values of the state. But if I setDisabled state in useEffect it goes into an infinite loop.
Can anyone tell me what is wrong with the code?
//This is how my state object and input fields looks.
const [state, setState] = useState({
items: [],
value: "",
error: null
});
<input
className={"input " + (state.error && " has-error")}
value={state.value}
placeholder="Type or paste email addresses and press `Enter`..."
onKeyDown={handleKeyDown}
onChange={handleChange}
onPaste={handlePaste}
/>
const handleKeyDown = evt => {
if (["Enter", "Tab", ","].includes(evt.key)) {
evt.preventDefault();
var value = state.value.trim();
if (value && isValid(value)) {
setState(prev => ({
...prev,
items: [...prev.items, prev.value],
value: ""
}));
}
//if my items array which is a count of emails i.e arrays of strings is greater than 3 I want to disable the input field.
if(state.items.length > 3){
setDisabled(true);
}
}
};
useEffect(()=>{
// if I set the disabled state which is an object inside the state param it goes into an infinite loop.
passStateToParent(state);
}[state])