poldeeek
poldeeek

Reputation: 333

how to show and hide popup only when promise is active ? React

I try to handle Handling account-exists-with-different-credential Errors on facebook login with firebase - firebase doc. Over the point 4a is var password = promptUserForPassword(); // TODO: implement promptUserForPassword. I tried to do it with promise, but honestly I have no idea how to render popup component in this situation...

For now I have this promise :

passwordAskPromise.then((password) => {
                            console.log(password)
                            firebase.auth().signInWithEmailAndPassword(email, password).then(function(userCredential) {
                                return userCredential.user.linkWithCredential(pendingCred);
                              })
                        })

promise code :

const passwordAskPromise = new Promise((resolve, reject) => {
    const setDecision = decision => {
        if(decision)
            resolve(decision)
        else
            reject(decision)
        }

    ReactDOM.render(<AskAboutPassword setDecision={(value) => setDecision(value)}/>, document.getElementById("popup"))
})

export default passwordAskPromise;

and AskAboutPassword:

const AskAboutPassword = props =>{ 

    const [password, setPassword] = useState('')

    return (
        <div className={styles.AskAboutPasswordContainer}>
            <input type="text" value={password} onChange={(e)=>setPassword(e.target.value)}/>
            <button onClick={() => props.setDecision(password)}>YES</button>
            <button onClick={() => props.setDecision(false)}>NO</button>
        </div>
    )
}

export default AskAboutPassword;

All logic works, but at this moment this "popup" is on the screen all the time beacuse I added <div id="popup></div> to my index.html file.

Upvotes: 2

Views: 1093

Answers (1)

Florian Motteau
Florian Motteau

Reputation: 3724

You could give a try to https://www.npmjs.com/package/react-promise-tracker, which provides a handy usePromiseTracker hook, returning true if a request is flying.

You can specify which promises should be tracked. It is mainly designed to display spinners or other visual feedback pour it should be useful in your case.

Wrap your promise to track its status :

import { trackPromise } from 'react-promise-tracker';

[...]

trackPromise(fetch(something));

// now react-promise-tracker keeps track of the promise returned by fetch(something)

Then in any component you can :

import { usePromiseTracker } from 'react-promise-tracker';
[...]

const MyComponent = () => {
  const { promiseInProgress } = usePromiseTracker();

  return (promiseInProgress ? <ComponentIfPromiseFlying /> : <OtherComponent />);
}    

Upvotes: 1

Related Questions