Reputation: 3512
I'm attempting to use useEffect
to set the initial value of a MUI TextField
on load. The value is being pulled from a database. This works the majority of the time however in some cases the useEffect
does not correctly update the value of the textfield
and it is just blank.
My Question: How can I change my code to make sure that the data being pulled from useEffect always sets the initial value of a textfield on load?
const [introText, setIntroText] = useState();
useEffect(() => {
const fetchResults = async () => {
const result = await axios({
method: "GET",
url: "https://server.site.com/userData",
withCredentials: true,
});
setIntroText(result.data.introEssayText);
};
fetchResults();
}, []);
<TextField
onChange={(e) => setIntroText(e.target.value)}
value={introText}
onInput={handleUpdatedIntro}
/>;
Upvotes: 1
Views: 1081
Reputation: 45923
"This works the majority of the time however in some cases the useEffect
does not correctly update the value of the textfield
and it is just blank".
Make sure result.data.introEssayText
is not empty for all use cases.
Other than that, having
const [introText, setIntroText] = useState()
would trigger the below warning for a normal input
which I believe TextField
would fall back to.
Warning: a component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
Instead use
const [introText, setIntroText] = useState("")
so the initial value of the input is ""
instead of undefined
.
Upvotes: 1