P
P
Pavel Didenko2021-04-02 00:16:00
React
Pavel Didenko, 2021-04-02 00:16:00

How to correctly use selectors from entityAdapters in redux-toolkit?

Created the post entity

const postsAdapter = createEntityAdapter({
    selectId: (post) => post.postId,
});


The posts are part of the feed side, there is more code, but I cut it out. essence will not change.
const feedSlice = createSlice({
    name: 'feed',
    initialState: {
        posts: postsAdapter.getInitialState(),
        lastPostId: undefined,
        loading: true,
        error: false,
    },
    reducers: {
        postUpdate: (state, { payload }) => {
            postsAdapter.updateOne(state.posts, payload);
        },
    },
});


Also created a selector
export const postsSelector = postsAdapter
    .getSelectors(({ feed }) => feed.posts);


And, accordingly, there is a component that renders the list of posts and the post component itself.

In the post, I get the post itself from the store through useSelector + post entity selector
const post = useSelector((state) => postsSelector.selectById(state, postId));


And after changing the post, by calling the action "updatePost" from the code above, the entire list of posts is rerendered. Just
in case, the Id list was also taken into the selector in the component that renders the list
const postsIds = useSelector((state) => postsSelector.selectIds(state));

But the result is the same, all posts are rerendered

And it’s not clear why the hell these adapter selectors exist if there’s no sense in them

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question