Steps for updating the same array in TypeScript

I have written a reducer code where I check if the same value is already present in the array. If it is, I update the previous value instead of pushing the same value again.

Here is my code snippet:

export function reducer(
      state: IDeviceState = initialState,
      action: DeviceActions.AllDeviceActions
    ): IDeviceState {
      switch (action.type) {
        case DeviceActions.GET_DEVICE_BY_ID_SUCCESS: {
          const { payload } = action;
          const devices = Array.isArray(payload)
            ? payload
                .map(pushBranches)
                .flat()
                .filter((device) => device !== null)
            : [pushBranches(payload)].filter((device) => device !== null);

          const updatedDevices = devices.filter((device) => {
            const existingDevice = state.devices.find(
              (d) => d.result?.unitId === device.result.unitId
            );

            return !existingDevice;
          });

          return {
            ...state,
            devices: state.devices.concat(updatedDevices),
            loading: false,
            loaded: true,
            error: null,
          };
        }
        default: {
          return state;
        }
      }
    }

    function pushBranches(devices: any) {
      if (devices.result) {
        return devices;
      }
      return null;
    }

Answer №1

It appears that your scenario involves handling an array of objects in your state, each with a unique key (presumably identified by the unitId property). The task at hand is to perform an "upsert" operation, where existing objects are updated or new ones inserted based on matching unitId.

The upsert process can be broken down into two main steps:

  • Remove any objects from the state that have a matching unitId found in the payload.
  • Add all objects from the payload to the state.

On a side note, naming your action as

GET_DEVICE_BY_ID_SUCCESS</code may not be very indicative of its purpose. Since actions are meant for modifying state, a more suitable name could be <code>DEVICE_UPSERT
or similar.

If your action can accept both single object payloads and arrays, you can streamline the process by converting the payload to an array if it's not already:

const payloadArray = Array.isArray(payload) ? payload : [payload];

This ensures that you're always working with an array while operating on payloadArray.

To handle the deletion phase of the upsert, where existing devices need to be removed, adjust your logic to filter out devices from the state that are present in the payload:

const remainingDevices = state.devices.filter(stateDevice => devices.every(
    d => d.result?.unitId !== stateDevice.result?.unitId
));

The resulting remainingDevices array will only contain devices that were not included in the payload. By using the every method, we ensure that no device with a matching unitId is retained in this array.

Finally, simply combine this array with the devices from the payload using concat to update the state with the new set of devices.

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

Using TypeScript: Union Types for Enum Key Values

Here's the code in the TS playground too, click here. Get the Enum key values as union types (for function parameter) I have managed to achieve this with the animals object by using key in to extract the key as the enum ANIMALS value. However, I am s ...

Encountering an error message stating "The variable 'App' is declared but not used" when running the index.tsx function

This React project is my attempt to learn how to use a modal window. The tutorial I've been following on YouTube uses JavaScript instead of TypeScript for their React project. However, I'm facing some challenges. Could you possibly help me ident ...

Utilizing ES6 Promises in Mongoose with Typescript to Create a Seamless Chain

When attempting to chain ES6 promises with Mongoose 4.5.4, I encountered an error in Typescript. public static signup(req: express.Request, res: express.Response) { UserModel.findOne({ email: req.body.email }).exec() .then(existingUser => { ...

Displayed even when data is present, the PrimeNg empty message persists

I have set up a PrimeNg table to display data with an empty message template like this: <ng-template pTemplate="emptymessage"> <tr> <td> No records found </td> </tr> </ng-template> ...

Tips for Effectively Declaring a Variable with React's useState

How should I correctly specify variable types in useState? In the code below, the value for alert must be either "success","warning", "error", or "info" const [alertValue, setAlertValue] = useState("error" ...

The solution to enabling Type checking in this scenario is simple: Begin by addressing the issue of "Not assignable," followed by resolving any

After subscribing to an observable projected by a BehaviorSubject from a service, I encountered the following errors when trying to assign the subscribed value to a local variable: error TS2322: Type '{}' is not assignable to type 'DatosAdmi ...

"Extra loader required to manage output from these loaders." error encountered in React and Typescript

After successfully writing package 1 in Typescript and running mocha tests, I confidently pushed the code to a git provider. I then proceeded to pull the code via npm into package 2. However, when attempting to run React with Typescript on package 2, I enc ...

Specify the object key type when using a `for-in` loop

My current situation involves an object type: interface ShortUrlParam { openid: string; avatar: string; nickname: string; } const param: ShortUrlParam = { openid: 'abc123', avatar: '', nickname: 'wenzi&apo ...

Can PHP Rewrite Array Elements?

What could be causing PHP to overwrite Array elements of objects with the last iteration of the object? This behavior raises concerns regarding maintaining a record of an object's changes using an array. It seems like this could lead to potential erro ...

Managing simultaneous asynchronous updates to the local state

There is a scenario where a series of asynchronous calls are made that read from a local state S, perform certain computations based on its current value, and return an updated value of the local state S'. All these operations occur at runtime, with ...

Testing a function within a class using closure in Javascript with Jest

Currently, I am attempting to simulate a single function within a class that is declared inside a closure. const CacheHandler = (function() { class _CacheManager { constructor() { return this; } public async readAsPromise(topic, filte ...

How to access JSON array data in PHP without using a loop to iterate through the keys

$c_array when printed displays the following data: Array ( [0] => Array ( [Category_Name] => sample quiz question 1 [Score] => 50 ) [1] => Array ( [Category_Name] => sample quiz question 2 [Score] => 100 ) ) <p>/<em>C ...

What is the best way to enhance @Query() dto with unfamiliar properties?

I have successfully created a table with pagination loading similar to the example provided in this tutorial. In my get controller function, I am currently utilizing @Query() pageOptionsDto: PageOptionsDto<PlayerSortColumn> as a parameter. This is t ...

I have noticed that my unit test case does not include coverage for the if statement

Here is the function I have in my TypeScript file: routeToIndividualPortal(sessionToken: string) { let redirectUrl = this.relayState; console.log("Pre-source-check Indivual URL : " + redirectUrl); let url = ""; if(redirectUrl.includes(this. ...

Incorporating timed hover effects in React applications

Take a look at the codesandbox example I'm currently working on implementing a modal that appears after a delay when hovering over a specific div. However, I've encountered some challenges. For instance, if the timeout is set to 1000ms and you h ...

Using JavaScript to place a particular tag at a designated position

I have a string that looks like this: var txtstr='<p>Text 1</p><p>&nbsp;</p><p>Text &nbsp;2</p><p>&nbsp;</p><p>Text 3&nbsp;</p>'; I have an <img src=..../> tag and ...

From PHP to JavaScript, the looping journey begins

Question I am attempting to display markers on a map using PHP to fetch the data, then converting it into JavaScript arrays for marker addition. Below is an example of my code: Database query require_once("func/connect.php"); $query = "SELECT * FROM sit ...

AngularJS Dilemma: Virtual Machine Data Set but No Rendering in Sight

Below is the AngularJS controller code written in Typescript: /// <reference path='../../definitions.d.ts' /> module baseApp.viewControls.products { export interface IProductsScope extends IAppScope { vm: { product ...

Receiving input from the user for a 2-D array in a specified format

I have a 2-D array with dimensions 6x6 named A. I am looking for user input in the format illustrated below: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Each 0 represents a position where the user should provide their values. ...

Struggling with setting up Angular Material and SCSS configuration in my application -

Hey there, I encountered an error or warning while trying to launch my angular app. Here's the issue: ERROR in ./src/styles/styles.scss (./node_modules/@angular-devkit/build- angular/src/angular-cli-files/plugins/raw-css- loader.js!./n ...