Combine Immer and NgRx reducer for improved state management

Upon analyzing redux and ngrx, it appears that immer is the preferred library for creating a copy of the state before storing it. In following the example provided by immer, I implemented the following code in my reducer:

  on(exampleActions.updateExample, (state, { example }) => {

    return produce((state: ExampleType, draft: ExampleType) => {
      draft.push({ example });
      draft[1].done = true;
    });

  })

However, TypeScript raises a no-shadowed-variable error, which clashes with the example given. Furthermore, I encounter issues with return-type errors when trying to return a value.

In scenarios where example is a multi-level object:

const example = {
  a: {
    b: { c: 1 }
  }
};

I realize that draft must be completely dereferenced as well.

There aren't many immersive examples available for integrating createReducer as this was a recent update for 2019. Should I disable the no-shadowed-variable rule for immer or is there a more effective approach to ensure that both state and example are correctly dereferenced, especially since example consists of nested objects?

As an alternative, I could opt out of using immer and utilize ramda's clone function or endeavor to manually deep-copy everything.

Answer №1

One way that ngrx-etc provides a solution is through the use of the mutableOn function, which leverages Immer for state management.

const entityReducer = createReducer<{ entities: Record<number, { id: number; name: string }> }>(
  {
    entities: {},
  },
  mutableOn(create, (state, { type, ...entity }) => {
    state.entities[entity.id] = entity
  }),
  mutableOn(update, (state, { id, newName }) => {
    const entity = state.entities[id]
    if (entity) {
      entity.name = newName
    }
  }),
  mutableOn(remove, (state, { id }) => {
    delete state.entities[id]
  }),
)

To explore the source code further, visit this link, which will guide you in the right direction.

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

Converting JSON data types into TypeScript interface data types

Struggling to convert data types to numbers using JSON.parse and the Reviver function. I've experimented with different options and examples, but can't seem to figure out where I'm going wrong. The Typescript interface I'm working with ...

Load Angular component on demand with necessary dependencies

Searching for an elegant solution (without resorting to private APIs) to create a widget-style dashboard. The goal is to dynamically load components based on user role. Is there a way to import a component and its dependencies included in the component&ap ...

Tips for testing the onEnter and resolve functions of a ui-router state

I need help testing an Angular UI Bootstrap modal that is triggered from the onEnter function in the state below: .state("profile.index.edit.services", { url: "/edit/services/:serviceCode", parent:"profile.index", onEnter: ['$ ...

Using a split string to destructure an array with a mix of let and const variables

There is a problem with TS: An error occurs stating that 'parsedHours' and 'parsedMinutes' should be declared as constants by using 'const' instead of 'prefer-const'. This issue arises when attempting to destructure ...

Removing classes from multiple elements on hover and click in Vue 2

Can Vue be used to remove a class from an element? I am looking to remove the class when hovering over the element, and then add it back once the mouse is no longer on the text. Additionally, I want the class to be removed when the element is clicked. He ...

Filtering out specific properties in an array using Angular

I am facing an issue with my Angular filter when inputting text for a specific list. initialViewModel.users = [ {user: 'Nithin',phone: 'Azus', price: 13000}, {user: 'Saritha',phone: 'MotoG1',price: 12000}, {user: ...

Stopping HTTP client calls in OnDestroy hook of an Angular Service

Is it possible to automatically unsubscribe from an http call in an Angular service using the ngOnDestroy hook? Just to note, I am already familiar with using the rxjs 'take' operator or manually unsubscribing from the service within the compone ...

Receiving the outcome of an asynchronous function in JavaScript

async function retrieveKey() { try { var key = await dec.awsDecrypt('dev-frontend') return key; } catch(err) { } } //calling the function const result = retrieveKey() In the code snippet above, there is an asynchronous ...

Unlocking the Sound: Using a Custom Button to Activate Audio on HTML Video in React

While working on a project, I encountered a small issue: I have a video tag in my code: <video muted autoPlay loop src={video}> I simply want to add a single custom button/control to toggle between muting and unmuting the video. I'm thinking of ...

Utilizing deployJava.runApplet for precise element targeting

After years of successfully maintaining an applet that utilizes the traditional: <script src="foo.js"></script> method for embedding a Java applet, we can no longer ignore the need for change. It's time to switch to: deployJava.runAppl ...

retrieving identifiers from a separate table for an array of values

As a newcomer to node and noSQL databases, I am facing challenges in grasping the concept of passing an array of IDs and retrieving the corresponding values from another table. I have 'users' and 'products' tables in my database. The st ...

Is it normal for e.target.result to only work after two or three tries?

Attempting to resize an image on the client side before sending it to the server has been challenging for me. Sometimes, the image does not align correctly with the canvas used for resizing. I have noticed that I need to send the resized image at least tw ...

Ways to manage the order of RequestExecutor execution

I have recently developed an intranet site using SharePoint Office 365. Within the master page file, there is a menu bar that utilizes a List to store the URL and name. My goal is to control the visibility of the "Admin" button based on whether the user ...

What methods can be used to secure Next.js API routes and prevent them from being directly accessed through the URL

I am seeking a solution for concealing the response data of next.js API routes when accessed through URL. I need to protect certain sensitive information from direct access by users. ...

Ways to incorporate padding into md-card using Angular 2 material

Need assistance with adding padding to md-card in angular2 material. I am using md-card to display my product list but struggling to add padding on them. Here's what I have tried: product.component.html : <p> Product List </p> <div ...

Important notice: Warning for stand-alone React 18 page regarding the import of createRoot from "react-dom"

I am in the process of developing a standalone webpage utilizing React 18: <!DOCTYPE html> <html lang="en"> <head> <title>Hello React!</title> <script crossorigin src="https://unpkg.com/react@1 ...

My AJAX function is not functioning as intended

I'm currently developing a time management system for my workplace. As I was coding, I implemented a feature that allows users to configure the database details similar to the setup process in WordPress. Once the data is saved successfully, I aim to d ...

Tips for transferring complete HTML content within a JSON payload

I've been working on a jQuery script to convert an entire HTML page into JSON text. My goal now is to transform this code into a JSON string. In the resulting JSON: The 'text1' value will store the complete HTML in a single string format ...

retrieve nodes from xml automatically

I am facing an issue with my JavaScript code where I need to extract all data from a specific node. I want to display all the nodes labeled 'ows_Person' on my website. Currently, I can only display one 'ows_person', but I need to iterat ...

Please make sure to utilize messageCreate instead of the deprecated message event

Hey there, I'm currently in the process of upgrading my discord bot from v12 to v13. The bot is up and running, all commands are loaded in the console, but I'm facing an issue where a notification keeps popping up at the bottom and none of my com ...