I'm trying to use a redux store state value in an input, but I have a custom useInput hook, that I can't figure how to make them work together.
I built a react custom useInput hook that handles the value, and change/blur events. Used like:
const {
value: titleValue,
error: titleError,
inputChangedHandler: titleChangedHandler,
inputBlurHandler: titleBlurHandler,
setValue: setTitleValue,
} = useInput(validateTitle);
<input
error={titleError ?? false}
id="title"
name="title"
type="text"
placeholder="Stream Title"
autoComplete="off"
value={titleValue}
onChange={titleChangedHandler}
onBlur={titleBlurHandler}
/>
my problem is that if I want to use it in an 'edit' components, which I want to fetch the initial values from an existing state, I cannot do it, because the input value is bound to the useInput value property.
so I can't do this, with my useInput custom hook:
const selectedItem = useSelector((state) => state.items.selectedItem);
<input
error={titleError ?? false}
id="title"
name="title"
type="text"
placeholder="Stream Title"
autoComplete="off"
value={selectedItem.title} <-- use the state selectedItem value
onChange={titleChangedHandler}
onBlur={titleBlurHandler}
/>
my useInput customer hook is just in charge of validation of the input value. It would work well if I could initially set the value to the store value, but my component is using useEffect to call an API getById(id) so the first time the component loads there is still no selectedItem, so I cannot initially set the useInput to the selectedItem.title.
this is my useInput custom hook code:
import { useState } from 'react';
const useInput = (validate) => {
console.log('in useInput');
const [value, setValue] = useState('');
const [isTouched, setIsTouched] = useState(false);
const validationResult = validate(value);
const error = !validationResult.isValid && isTouched && validationResult.message;
const inputChangedHandler = (event) => {
setIsTouched(true);
setValue(event.target.value);
};
const inputBlurHandler = () => {
setIsTouched(true);
};
return { value, error, inputChangedHandler, inputBlurHandler, setValue };
};
export default useInput;
How can I fix it?