简体   繁体   中英

State not updating in React Fetch function

I have a state, that is set to be either true or false in a fetch statement. When the fetch statement is called, the state is not updated until the second time the submit button is pressed.

It is because of that, that whenever I call an if statement right after, my code automatically navigates to my home page, thinking that the adding of a new account is successful.

When I try to set the state to null or false , the ternary statement automatically fires off as well.

I've checked the data by console logging it, and it comes back as "false" when applicable, but still never updates the state

Any insight on how to approach next?

Edit: The fetch is returning a boolean

    let navigate = useNavigate();

    // Error states
    const [successfulAdd, setSuccessfulAdd] = useState(true);


    // Function
    function handleRegister(e) {
        const user = { firstName, lastName, email, password, phone, userName, isAdmin };

        if (password !== passwordConfirm) {
            setPasswordMatch(false);
        } else {
            fetch("http://localhost:8080/user/add", {
                method: "POST",
                headers: { "Content-type": "application/json" },
                body: JSON.stringify(user),
            })
                .then(response => response.json())
                .then(data => setSuccessfulAdd(data));
        }

        if (successfulAdd) {
            navigate("../home");
        }
    }
.
.
.
    return (
.
.
.
         {/* Username Checker */}
         {successfulAdd ? "" : <div class="alert alert-danger" role="alert">
              The username you've entered has been taken
         </div>}
.
.
.
)

Since Fetch API and setState are both asynchronous, you might want to put the if statement and all logic inside.then(…)

fetch(…)
 .then(res => res.json())
 .then(json => … //navigate here)
 .catch(err => … //set your error state here)

First, you can set the initial state to undefined .

const [successfulAdd, setSuccessfulAdd] = useState(true);

Second, add the navigate logic in then of the fetch request .

 .then(data => { if(data) { navigateTo("./home") } })

At last, you can check if successfulAdd is false then show the user taken message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM