简体   繁体   中英

Update state only on OK, revert back to previous state on CANCEL

I have a react app similar to what is shown in this codesandbox link https://codesandbox.io/s/eatery-forked-t44bx?fontsize=14&hidenavigation=1&theme=dark

Clicking the Menu at the bottom center of the page renders the MenuFilter component.

The way I have it now, checking the checkbox immediately updates the checked items. This is good from a user interface point of you. User gets instant feedback on what he is clicking on (what is getting un-clicked if something is getting un-clicked).

The problem with though is that the OK/Cancel button loose there use. In other words, after making changes to the selection, if the user decides that we does not want any of these new selection & rather revert back to old selection (the one before the Menu button was clicked), he cannot do that because all the states have been updated (updating happens as the check boxes are being clicked).

How to update the state ONLY if OK (currently only CANCLE button is working, so you can consider that) button is clicked. However, the check-marks should none the less change as the user is clicking them.

Is there a way to do this other than creating a 'temporary' state (I don't want to do this) to update the visual changes & only when a button is clicked, the changes are done one the data.

You can change the checkedItems to a local state of the MenuFilter component, and pass it as an argument on onClick . That way, when you open the modal, the component mounts again and the state should return to its default.
Something like:


export const MenuFilter = ({ onClick, onCheck }) => {
  const [checkedItems, setCheckedItems] = useState(["allItems"])

  return (
    <button onClick={() => onClick(checkedItems)}>Cancel</button>
  )
}

Edit : You'll still need some sort of state to handle the data on the parent component, but you won't have to manually handle resetting the data.

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