If validation to check if value is Undefined

Asked

Viewed 71 times

-1

I’m having trouble checking if the value is undefinded. I need to make a if for this validation, follow my code:

My interface:

interface IModalContatos {
  dados: IContatos | undefined;
  onSave:(dados: IContatos) => void;
  onClose:() => void;
}

Man state (state):

const [contatoAtualizado,setContatoAtualizado]=useState<IContatos>(dados as IContatos);

Validation:

useEffect(() => {
    if (dados === undefined) {
    }
    setContatoAtualizado(dados as IContatos)
}, [dados]);
  • I believe you wanted to return the data as Undefined when there is no iContatos, in this case is a double pipe: dados: IContatos || undefined;

  • You can also return this, it will result in boolean: true / false: return (!!IContatos);

  • I don’t quite understand what you want to do. Could you try [Edit] the question to clarify what your goal is? You just want to update the state if dados is different from undefined? Then it wouldn’t be enough to put the setContatoAtualizado(dados) within the if, also changing it to if (dados !== undefined) { ... }?

1 answer

-1

You can try using the operator typeof. For example :

if (typeof dados === "undefined")

Apparently every time undefined you want to run setContatoAtualizado right? If that’s what you can try to use on useEffect already passing this condition, something like:

useEffect(() => {
  if (typeof dados === "undefined"){
    setContatoAtualizado(dados as IContatos);
  }
}, [dados]);
  • 1

    I don’t think that pass the typeof dados === "undefined" in the dependencies array of the useEffect is a good idea. In addition to not helping Typescript to infer the "nullity" (whether it is null or not) of dados, can end up creating unexpected behaviors. Also, as far as I know, the dependency array is not meant to be used that way (although, in that last statement, I might be wrong).

  • I actually made a mistake, the dependency array is not made for this kind of use, editing for only if use within useEffect.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.