React, fetch and custom modal

Viewed 229

First of all, I'm new to coding and I'm VERY very new to React, so please, I need help.

I created a login (connected to firebase) and it works alright. When I submit the form, I have a feedback (an alert) that tells me if the login was successful and, if not, what was the error.

Now, I've created my own modal component and I want the feedback message to be delivered with that modal, and that's what I'm absolutely not able to do.

I wanted to use a global variable (message) inside the fetch to store a string (that tells me if the auth went right or wrong) and then use that variable inside my custom modal component... but I figured it was not possible.

I did some research on using async-await with fetch but could not make it work whatsoever, so I have no clues now on what to do now :( Here's my code, this is my SubmitHandler function:

let message = null;

const submitHandler = (event) => {                             

event.preventDefault();

const enteredEmail = emailRef.current.value;                 
const enteredPassword = passwordRef.current.value;          

emailReset();    
passwordReset();

setIsLoading(true);    //loading animation                                       

const url = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=API";

fetch(url, {                                                
  method: 'POST',                                           
  body: JSON.stringify({                                    
    email: enteredEmail,                                     
    password: enteredPassword,
    returnSecureToken: true,
  }),                                                        
  headers: {                                                  
    'Content-Type': 'application/json',
  },                                                          
})                                                            
  .then((res) => {                                            
    setIsLoading(false);                                     
    if (res.ok) {                                             
      return res.json();                                     
    } else {                                                  
      return res.json().then((data) => {                   
        let errorMessage = 'Authentication failed';
          if (data && data.error && data.error.message) {     
            errorMessage = data.error.message;                
            switch (errorMessage) {
              case 'INVALID_PASSWORD': 
                errorMessage = 'The entered password is invalid'
                break;
              case 'EMAIL_NOT_FOUND': 
                errorMessage = 'the entered email is not valid'
                break; 
              default:
                errorMessage = 'Authentication failed';
            }
          }
        throw new Error(errorMessage);                        
      });                                                     
    }                                                         
  })
  .then((data) => {                                          
    authCtx.login(data.idToken);                                                                                      
    const okmessage = 'Authentication succeeded!';  

    history.replace('/'); 
    message = okmessage;  
    alert(message);                 
  })
  .catch((err) => {                                           

    message = err.message;
    alert(message);
    
  });};

and this is what the form-submit button inside the return:

  <button onClick={() => setIsOpen(true)}> <i className="bi bi-box-arrow-in-right"></i> Login</button>       
    {message && (<Modal isOpen={isOpen} close={() => setIsOpen(false)}>
      <p>{message}</p>
    </Modal>)}

Thanks to anyone who'll try to help

0 Answers
Related