Home > Net >  how to update a single value from object depending on the state value in React/Next?
how to update a single value from object depending on the state value in React/Next?

Time:09-02

In my context api i've set an object and when the user clicks the state will change. and i want to update that specific value with the state value.

const initialState = {
    notification: false,
    setting: false,
    profile: false,
}

export function ContextProvider ({ children }) {
    const [isClicked, setIsClicked] = useState(initialState);
    const handleClick = (clicked) => {

     // change the static value 'true' to dynamic value of the initialState clicked 
     // value to opposite. like if user selects 'profile' it changes to it's value 
     // opposite. but only one value can be true. b/c i don't want to keep it open 
     // when other nav is selected

        setIsClicked({ ...initialState, [clicked]: true});
    }
   ...
} export default StateContext;

in my NavBar.js

const NavBar = () => {
    const { isClicked, setIsClicked } = useContext(StateContext);
    ...
    return (
    ...
        {isClicked.notification && <Notification />}
        {isClicked.profile && <Profile />}
        {isClicked.setting && <Setting />}
    ...
    )
}

so how can i make the nav bar work this way. NB: only one value can be true in that object.

CodePudding user response:

Please try this way

setIsClicked(prevState => ({
        ...prevState,
        [clicked]: !prevState[clicked]
    }));
  • Related