0

I was not able to get exact state value for first instance. I getting the state of first instance in second instance.

My code performs:

  1. Add new users to database.
  2. Ignoring old users if users are already present in database.
  3. Send mail to new users after adding to database.

Expected: Add user to database & Send mail if user is not present in database. console.log("user exists") if user is already present in database.

Can someone tell me how can i get the expected result

Here is the code

import emailjs from "emailjs-com";
import React,{useState, useEffect} from 'react';
import firebase from '../firebase';

export default function Subscribe() {

const [Email, setEmail] = useState("");
const [status , setStatus]= useState();

const addLocation = data => firebase.database().ref().child('Subscribers').push(data, response => response);
const updateLocation = (id, data) => firebase.database().ref().child(`Subscribers/${id}`).update(data, response => response);

const actions = {
  addLocation,
  updateLocation,
};

function handleText(e)
{
        setEmail(e.target.value);
        
}
//console.log(Email);


function sendEmail(e) {
     
  e.preventDefault();
  
  checkDatabase();
  

  if(status)
        {
          console.log(e.target);
          console.log("mail sent");
        emailjs.sendForm('service_vq18lse', 'template_subscribe', e.target, 'user_9Nxm9mXbOkViTWV2xpkRd')
        .then((result) => {
            console.log(result.text);
        }, (error) => {
            console.log(error.text);
        });
        }
 else{
   console.log("user already exists")
 }

}

function checkDatabase() {
        
        firebase.database().ref().child("Subscribers").orderByChild('email').equalTo(Email).once("value", snapshot => {
           
          const userEmail = snapshot.val();
          console.log(userEmail);

          if (userEmail){
            //console.log("user exists!");
            setStatus(false);
            } 
          else {
            //addLocation({email: Email});
            //console.log(" new user found!");
            //console.log(e.target);
            setStatus(true);
          }
          });

    }

    
  
 
    return(
    
        <div className="container">
        <form onSubmit={sendEmail}>
                <div className="row pt-5 mx-auto">
                   
                    <div className="col-8 form-group pt-2 mx-auto">
                        <input type="email" className="form-control" placeholder="Email Address" name="user_email" onChange={handleText}/>
                    </div>
                   
                    
                    <div className="col-8 pt-3 mx-auto">
                        <input type="submit" className="btn btn-info" value="Subscribe"></input>
                    </div>
                </div>
        </form>
        </div>
    )
}

  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Brian Thompson Nov 24 '20 at 17:22

1 Answers1

0

The react useState, keeps the changes on a Stack to be updated, so it´s not immediate. The best way to get the new state, is to put a useEffect that detects when the (Add user to database) action occurs and then set the variable.

Mvrocha
  • 393
  • 3
  • 14