简体   繁体   中英

React Hooks - useState does not update “Saving…”, “Saved” states immediately

I'm using React Hooks and I'm creating a page such that users can make changes to their account and save it. When the page loads, I want the button to be disabled because the page will show the previously saved information and there's no need to save since no changes were made. Once the user makes a change, I have a validate() function that will check if whatever changes they made are valid. If they are then, the button should be enabled. When the user clicks the save button, the button should be disabled and "Saving" should show. Once it's done saving, the button should still be disabled and "Saved" should show.

I have 3 state variables that are initialized like so (disableButton is true at first because the button is disabled on landing the page).

const [saved, setSaved] = useState(false);
const [isSubmitting, setSubmitting] = useState(false);
const [disableButton, setDisableButton] = useState(true);

I used setState when certain events occur, for example, when the user clicks the save button:

const handleSubmit = async () => {
    setSaved(false);
    setSubmitting(true);
    setDisableButton(true);
...
}

I noticed that these changes aren't made immediately, but the next time it renders, which is a problem for me. I looked into useEffect as well, but I'm not sure if it will work in my case (or maybe I'm just not seeing a pattern). I'm new to React so any help would be appreciated.

All state updates in React are asynchronous by design as to try and batch events together instead of triggering a render per change.

Class based component have a way to React to state updates via a setState callback:

onEvent = () => {
    this.setState({ key: value }, () => {
        console.log("I'm run when the state has been updated!");
    }); 
}

For function components, the principle still applies although in a different way:

export const SomeComponent = () => {
    const [value, setValue] = useState(false);

    useEffect(() => {
        console.log("I'm run whenever value changes!");
    }, [value]);

    function onEvent() {
        setValue(!value);
    }

    // ...
}

That's how this is designed so you will have to find a way to make it work for your use case. Feel free to add more detail about your particular situation.

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