Home > database >  How get one record from storage?
How get one record from storage?

Time:09-19

I want to receive a post by id. But I have a problem that if I open one message first and then open another message, then the other record will just be added to the state and it will look like this. Although only one entry should be displayed.

How to fix it?

reducer:

const postReducer = createReducer(
  initialState,
  on(loadPostSuccess, (state, action) => {
    return postAdapter.setOne(action.post, state);
  })
);

export function PostReducer(state: PostState | undefined, action: Action) {
  return postReducer(state, action);
}

state:

export interface PostState extends EntityState<Post> {}

export const postAdapter = createEntityAdapter<Post>({
  selectId: (post: Post) => post.post_id,
});

export const initialState: PostState = postAdapter.getInitialState({});

selector:

const selectPostState = createFeatureSelector<RequestState>(REQUEST_STATE_NAME);

export const selectRequest = createSelector(
  selectPostState,
  (state) => state.post
);

export const selectRequestEntities = createSelector(
  selectRequest,
  (state) => state.entities[state.ids[0]]
);

CodePudding user response:

If you just want to keep one entity in the state, I think you shouldn't be using ngrx entity.

That being said, you can do the following as an answer to your question.

return postAdapter.setAll([action.post]), state);

The better answer is saying that it's ok to hold more entities in state because it has benefits, and you can use retrieve the selected item by its id if it's stored in the URL.

https://timdeschryver.dev/blog/parameterized-selectors

  • Related