What is the best way to utilize createEntityAdapter in order to incorporate selectors within slice reducers?

Currently, I have all my adapters defined in a centralized file and exporting them from there. In my slice, I export a selectors object that includes selectors generated by my entityAdapter. Since the entityState is nested within the slice state, I've defined the selectors as follows:

const entitySelectors = myAdapter.getSelectors<RootState>((state) => state.sliceState.entities)

I want to use these selectors in the reducers of the same slice they are exported from, so I don't duplicate logic already provided by the adapter. Is there an efficient way to achieve this without defining two versions of the selectors (one for RootState and one for SliceState)?

One approach could be:

const sliceStateSelectors = myAdapter.getSelectors<SliceState>((state) => state.entities);
const rootStateSelectors = myAdapter.getSelectors<RootState>((state) => state.sliceState.entities);

export const selectors = {
...rootStateSelectors,
// other selectors
}

This setup allows me to use sliceState selectors in my reducers, but it may not be ideal in terms of clarity and avoiding repetition.

Answer №1

While a Redux selector typically takes the entire Redux root state object as input, it's important to remember that a slice represents only a portion of that state. Therefore, if you plan on utilizing selectors within reducers, you'll need to develop alternate versions capable of accepting just the slice state.

However, I would caution against incorporating selectors directly into a slice's reducers. This approach doesn't offer any significant advantages. It's simpler to access specific items using state.entities[someId] rather than relying on selectById(). Additionally, the logic for how these items are stored is managed by the slice's reducer itself.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to combine two .csv files using JavaScript?

My situation involves having a pair of .csv files that resemble the following example: date,type,brand,model,price 2014-11-27, electric, tesla, model s , 100000 2014-11-27, diesel, bmw, m3, 90000 2014-12-13, hybrid, toyota, yaris , 20000 How do I go ...

Having trouble iterating over fields of an interface in TypeScript?

I am currently facing an issue while trying to loop through the keys of an object that contains an interface. TypeScript seems to be unable to recognize the type of the key. interface Resources { food?: number water?: number wood?: number coal?: n ...

The specialized element encountered an issue with mapping

For a while now, I've been trying to create my own custom component but it's not working as expected. The interaction seems fine, but for some reason, it only renders the last item in the arrays. export default class MyComponent extends Comp ...

React-modal triggers the file-explorer upon exiting the dropzone

Within my project, I have implemented a button that triggers a modal to appear on mouse-over. This button is nested inside a dropzone element. https://i.sstatic.net/95dxy.png The issue arises when I exit the modal by clicking (not exiting with the escape ...

Can you identify any issues with this Javascript code's "If" condition?

In my JavaScript code, I have an "if condition" that looks like this: for (var i in data) { //Gender.push("Gender " + data[i].JenisKelaminID); if (data[i].JenisKelaminID == 1) { Gender.push("Men"); } if (data[i].JenisKelaminID == 2) { Gend ...

Angular gaining mastery over the Form

Here's a snippet of code for a form I'm working on: <form name="registerForm" novalidate role="form"> <div class="row"> <div class="small-3 columns"><label for="pwd" class="right inline">Password:</label> ...

Disable page scrolling while enabling scrolling for specific elements with overflow using JQM

Is there a way to stop the page from scrolling on a jQuery Mobile page while still allowing a specific element with overflow set to scroll to be scrolled by the user? The challenge is that the length of the page may vary slightly, exceeding 100% on differe ...

Find elements in an array that match certain key values

Currently, I am working with an array that requires me to filter out specific keys without looping through them. I have created separate filters for each key needed: this.filteredCampaigns = this.allCampaigns.filter( (item) => item.status?.includes(tr ...

Steps for declaring CSS values with fallbacks in case of unsupported values

I'm looking to utilize the overflow: overlay property in Chrome, and overflow: scroll in Firefox. Simply declaring the overlay value causes Firefox not to scroll at all, even though I know it's not standard. My question is: what's the optim ...

The onChange function in CustomSelect is triggering an endless loop of renders in a React application using TypeScript and Material-

Currently, I am working with a mui element called CustomSelect. It functions perfectly on desktop, however, the handleChange function from onChange only console logs once. On mobile (even in development mode), it renders 51 times before crashing and displa ...

Altering the DOM directly within the componentDidMount() lifecycle method without needing to use

In ReactJS, I am facing an issue while trying to manipulate the DOM in the componentDidMount() method. The problem lies in the fact that the DOM is not fully rendered at this point, requiring me to use a setTimeout function, which I find undesirable. Upon ...

Crafting an integrated REST API model with interconnected data

This question revolves around the implementation of a specific scenario rather than a problem I am facing. Let's say we have a User and a Resource, where a User can have multiple Resource but a Resource can have only 1 User. How should API endpoints b ...

Error encountered within the mounted hook in threejs referencing issue

After successfully importing a js file with three.js code into a standard HTML file, I attempted to export/import the code from the external JS file and call it from mounted. However, when doing so, I received an error message stating: "ReferenceError: THR ...

Error: Unable to find the specified module '/node_modules/.vite/deps/bootstrap.js' because it does not have a default export

Whenever I try to import Bootstrap into my React project like this: import bootstrap from "bootstrap"; I encounter the following error: Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/bootstrap.js?t=1693123714754&v= ...

Having trouble aligning a div in the middle of a slick-slider item using flex styling

I've created a slick slider component in Vue, and I'm facing an issue with centering a circular div inside each of the slider items. Despite trying to align and justify center along with adding margin:auto for horizontal centering, I can't s ...

How to adjust chart axis in Chartist.js to start 10 units above the minimum value and end 10 units below the maximum value?

How can the x-axis on a chartist line graph be adjusted to not start at 0, but instead begin 10 units below the minimum value and end 10 units above the maximum value? Currently, regardless of the minimum number, it always starts at 0. https://i.sstatic.n ...

The jQuery function creating an object that calls itself as a method

Currently, I am in the process of developing a Jquery game for my school project. In order to make the create() function recall itself, I have included a setTimeout() at the end of the method. However, it seems that the function is only running once when ...

Changing the format of a data structure using JavaScript/TypeScript

Hey there, I have a rowdata that looks like this: export const ROWDATA: Array<any> = [ { id: "1", start_time: "9:00:00", end_time: "9:30:00", day_of_week: 'monday', lesson: "Lesson ABC", ...

Generating intricate arrays from a given list

If I have an array containing various items like the following: [ ["Core", "Mathematics", "Mathematics 20-4"], ["Core", "Mathematics", "Mathematics 30-1"], ["Other", "Fine Arts", "Art", "some art course"], ["Other", "Fine Arts", "Music", " ...

An unexpected error has occurred in the browser console: The character '@' is not valid

I recently made the decision to dive into learning about Unit Testing with JavaScript. To aid in this process, I started using both Mocha.js and Chai.js frameworks. I downloaded the latest versions of these frameworks onto my index.html from cdnjs.com. How ...