-
How to transform the following redux code with valtio? interface Todo {
id: string;
title: string;
active: boolean;
createdAt: number;
}
interface RootState {
[scope: string]: Record<string, Todo>;
} Suppose I have the above data structure I want to get The implementation code using redux is as follows, and bailout can be implemented by shallowEqual const UseRedux: FC<{ scope: string }> = ({ scope }) => {
const selector = useCallback(
(state) => {
const todos = state[scope];
return Object.values(todos)
.filter((item) => item.active)
.map((item) => item.id);
},
[id]
);
const activeIds = useSelector(selector, shallowEqual);
return (
<ul>
{activeIds.map((id) => (
<Item id={id} />
))}
</ul>
);
}; I don't know how to achieve the above effect in valtio, const rootState = proxy<RootState>({});
const UseValtio: FC<{ scope: string }> = ({ scope }) => {
const derived = useMemo(() => {
const selector = (state: RootState) => {
const todos = state[scope];
return Object.values(todos)
.filter((item) => item.active)
.map((item) => item.id);
};
return derive({
activeIds: (get) => selector(get(rootState)),
});
}, [scope]);
const activeIds = useSnapshot(derived).activeIds;
return (
<ul>
{activeIds.map((id) => (
<Item id={id} />
))}
</ul>
);
}; |
Beta Was this translation helpful? Give feedback.
Answered by
dai-shi
Feb 16, 2022
Replies: 1 comment 4 replies
-
It depends on your goal, but I would simply do this: const UseValtio: FC<{ scope: string }> = ({ scope }) => {
const todos = useSnapshot(rootState[scope]);
const activeIds = Object.values(todos)
.filter((item) => item.active)
.map((item) => item.id);
return (
<ul>
{activeIds.map((id) => (
<Item id={id} />
))}
</ul>
);
}; But, you probably concern some extra re-renders? |
Beta Was this translation helpful? Give feedback.
4 replies
Answer selected by
uinz
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It depends on your goal, but I would simply do this:
But, you probably concern some extra re-renders?