Home > Blockchain >  Change State - React
Change State - React

Time:01-19

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?

CodePudding user response:

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]);

CodePudding user response:

if(form.name) changeTitle(form.name);
  •  Tags:  
  • Related