Ana Aimar
Ana Aimar

Reputation: 11

Change State - React

I define a state like this,

const [title, changeTitle] = useState('');

So, the value of the variable Title is an empty string.

Then, I receive a JSON, form :{active: '1', name: 'New Form', …}

I need to change the state title to New Form. changeTitle(form.name);

But then, the variable Title is undefined.

What am I doing wrong?

Upvotes: 0

Views: 67

Answers (1)

Hakim Abdelcadir
Hakim Abdelcadir

Reputation: 1326

Make sure that when you call changeTitle the variable form.name is not undefined. If you are using react hooks and the variable form is a state or prop you can use a useEffect and change the state of title only when the variable form.name is defined

useEffect(() => {
 if(form.name){
  changeTitle(form.name);
 }
},[form.name]);

Upvotes: 3

Related Questions