0

I'm getting a problem with useState(). The problem is whenever the page refresh userId has no value because I set it but inside my code I acquire it's value.

const [userId, setUserId] = useState("");

function registerUser(e){
        e.stopPropagation();
        e.preventDefault();

        if (isAdmin == "select permission" || isAdmin == null || isAdmin == undefined || isAdmin == "") {
            Swal.fire({
                icon: "warning",
                title: "Error message!",
                text: "Please select a permission to proceed!"
            })
        } else if(department == "select department" || department == null || department == undefined || department == "") {
            Swal.fire({
                icon: "warning",
                title: "Error message!",
                text: "Please select a department to proceed!"
            })
        } else if(position == "select position" || position == null || position == undefined || position == "") {
            Swal.fire({
                icon: "warning",
                title: "Error message!",
                text: "Please select a position to proceed!"
            })
        } else {
            fetch('http://localhost:4000/api/users/email-exist', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                // API only accepts
                body: JSON.stringify({
                    email: email
                })
            }).then(res => {
                return res.json()
            }).then(gatheredData => {
                if (gatheredData === false) {

                    fetch('http://localhost:4000/api/users/register',{
                        method: 'POST',
                        headers: {
                        'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            firstName: firstName,
                            lastName: lastName,
                            department: department,
                            position: position,
                            email: email,
                            mobileNo: mobileNo,
                            isAdmin: isAdmin,
                            password: "password123",
                            departmentId: departmentId
                        })
                      }).then(res => res.json()).then(convertedData => {

                        if(convertedData === true){

                            fetch('http://localhost:4000/api/users/get-id',{
                                method: 'POST',
                                headers: {
                                'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({
                                    email: email
                                })
                            }).then(res => res.json()).then(userData => {
                                setUserId("");
                                console.log(userData)
                                setUserId(userData);
                                console.log(departmentId)

                                if(userData === "" || userData === undefined) {
                                    alert("Error")
                                } else {
                                    fetch(`http://localhost:4000/api/users/enroll/${departmentId}`,{
                                        method: 'POST',
                                        headers: {
                                        'Content-Type': 'application/json'
                                        },
                                        body: JSON.stringify({
                                            agentId: userId
                                        })
                                    }).then(res => res.json()).then(enrolled => {
                                        console.log(enrolled)
                                        if (enrolled === true) {
                                            Swal.fire({
                                                icon: "success",
                                                title: "Congratulations!",
                                                text: "Account has been created successfully."
                                               })
                                        } else {
                                            Swal.fire({
                                                icon: "success",
                                                title: "Warning!!",
                                                text: "Account has been created but not linked to any departments."
                                               })
                                        }
                                    })
                                }
                            })
                        } else {
                            Swal.fire({
                                icon: "error",
                                title: "Error message!",
                                text: "Something went wrong, please try again later."
                            })
                        }
                    })
                } else {
                    Swal.fire({
                        icon: "warning",
                        title: "Error message!",
                        text: "Email address has already been used!"
                    })
                }
            })
        }
    }

What the system does:

  1. Create a User
  2. Get the Users Id
  3. Update Department array to add the User as it's agent.

What is the error that I'm getting:

  1. Whenever the page refreshed and create a new user I'm getting error messages with userId and it says the value is null and the registration will pushed through because that's how I designed it and it's id will be displayed in the consoled tab for testing but I'm no longer able to proceed with step 2 and 3.
  2. If I don't refresh the page and create a new user again, it's id will be displayed and will proceed with step 2 and 3 but the id that will be stored to my agent's array from the department document is the previous id that was generated from the previous user created.

Please help :-)

2
  • refreshing page actually SHOULD remove all the data react is holding. if u want to persist data in-between refreshes then use sessionStorage. Commented Jul 5, 2021 at 10:14
  • Thanks. I understand it now. Commented Jul 5, 2021 at 11:21

1 Answer 1

0

There are two things,

  1. Refreshing page actually SHOULD remove all the data react is holding. If u want to persist data in-between refreshes then use sessionStorage

  2. Setting a value via useState hook shows the value AFTER a render. So, you cannot do setUserId and in the next promise agentId: userId and expect to get the updated value. You will get the last value.

So instead of agentId: userId do agentId: userData that should be a quick fix.

Sign up to request clarification or add additional context in comments.

1 Comment

Got it. That's why I get the same issue on my other page. Really appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.