Home > OS >  Javascript how to rename a variable in array deconstructor
Javascript how to rename a variable in array deconstructor

Time:12-21

I have a deconstructured array of values, as instructed in the docs. (react-firebase-hooks)

const [ signInWithEmailAndPassword, loading, error] = useSignInWithEmailAndPassword(auth);

All is fine, but what if I have another hook with the same return keys:

const [ signInWithEmailAndPassword, loading, error] = useSignInWithEmailAndPassword(auth);  
const [ signInWithGoogle, loading, error ] = useSignInWithGoogle(auth);

As I cannot redeclare variables, how would I solve this?

I want to eventually return a spinner, if either loading value is true.

What I tried: Assigning a new variable name inside the deconstructor.

What I was expecting: My expectations were open.

CodePudding user response:

You can reassign the names like this:

const [ signInWithEmailAndPassword, loading, error] = [true, true, false];
const [ signInWithGoogle, gLoading = loading, gErr = error ] = 
  [`Hello`, false, `error!`];
console.log( `${signInWithEmailAndPassword}, ${loading}, ${error}\n${
  signInWithGoogle}, ${gLoading}, ${gErr}`);

CodePudding user response:

you don't have to do it like this:

const [ signInWithEmailAndPassword, loading, error] = useSignInWithEmailAndPassword(auth);

simply replace it with

 const signinObject = useSignInWithEmailAndPassword(auth);
 // do what you need with loading 
 signinObject[1]
 // do what you need with error
 sigininObject[2]

the the destruction only take it out from the array, but this way you keep it as array and refer to its index

  • Related