Yohav Rn
Yohav Rn

Reputation: 209

useState of props undefined in React

I'm trying to give a value of the props note to the TextField but if I use TextInput the result is undefined and if I use the note props, I cannot change the value of the TextField afterward. When I console log both of the value, they render twice as shown in the image. I tried useEffect also to set the state.

export default function ProfileNote({ contact }) {
  const { note, id } = contact;
  const [textInput, setTextInput] = useState(note);
  
  console.log(`textInput:  ${textInput}`)
  console.log(`note:  ${note}`)  

  const handleTextInputChange = event => {
    setTextInput(event.target.value);
  };

return (
    <FormProvider onSubmit={handleSubmit(onSubmit)}>
       <TextField
         name="notes"
         label="Notes"
         onChange={handleTextInputChange}
         value={textInput}
       />
    </FormProvider>
  );
}

Image of the console.log

enter image description here

Thank you.

Upvotes: 2

Views: 1945

Answers (1)

Steffen Frank
Steffen Frank

Reputation: 1797

I assume that the code that calls ProfileNote receives the contact asynchronously from a database or an API. When the asynchronous call is started, the value of contact.note is still undefined, but your component is still rendered.

This undefined value is now used as the initial value for textField. Once the asynchronous function call returns with a value (e.g. ddfdf), the textField value will not be changed since it is already initialized.

You can do one of two things in order to fix this, dependent on how you want your UI to behave:

  • prevent rendering the ProfileNote until the data is available:
<>
{ contact != null && <ProfileNote contact={contact}/> }
</>
  • continuously apply changes to contact.note to textField, potentially overwriting user input if contact changes while the user is editing:
useEffect(() => setTextInput(note), [note]);

Upvotes: 2

Related Questions