how to change two status attr with two func and get new statue #1710
Replies: 2 comments
-
@caichuanwang Try using different selectors for each of the states rather than using the same setState(). You should use import { atom, selector } from "recoil";
interface User {
modalStatus: {
a?: unknown;
};
refresh: boolean;
}
export const userState = atom<User>({
key: "userState",
default: {
modalStatus: {},
refresh: false,
},
});
// to change the modalStatus
export const setModalStatusSelector = selector({
key: "setModalStatus",
get: ({ get }) => {
const modalStatus = get(userState).modalStatus;
return modalStatus;
},
set: ({ set, get }, newValue) => {
const refresh = get(userState).refresh;
return set(userState, { refresh, modalStatus: { a: newValue } });
},
});
// to change the refresh state
export const setRefreshSelector = selector({
key: "setRefreshSelector",
get: ({ get }) => {
const refresh = get(userState).refresh;
return refresh;
},
set: ({ set, get }) => {
const { refresh, modalStatus } = get(userState);
return set(userState, { modalStatus, refresh: !refresh });
},
}); |
Beta Was this translation helpful? Give feedback.
-
Yes, breaking up state is often a great idea. For example, the modal status and refresh could be separate atoms. If you do deal with compound state and want to just update part it is recommended to use the updater form of setters by passing in a callback that gets the current state as the first parameter: const refreshTable = () => {
setUserStatus(userStatus => ({
...userStatus,
refresh: !refresh,
}));
}; |
Beta Was this translation helpful? Give feedback.
-
eg:
i have one state
export const userState = atom({
key: 'userState',
default: initialState,
});
const initialState: User = {
modalStatus: {},
refresh: false,
};
and i have two func is
const [userStatus, setUserStatus] = useRecoilState(userState);
const setClose = () => {
setUserStatus({
...userStatus,
modalStatus: {
a: false,
},
});
};
const refreshTable = () => {
setUserStatus({
...userStatus,
refresh: !refresh,
});
};
and i call there in one palce
setClose();
refreshTable();
but where call func refreshTable ,userStatus is not {a:false}
why?
Beta Was this translation helpful? Give feedback.
All reactions