Having trouble organizing the state tree in NGRX as I envisioned it

Currently, I am using ngrx to manage the state in my application. I recently attempted to introduce a new property called selected shifts which should have a specific structure.

state: {
    shifts: {
        selectedShifts: [
            [employeeId]: [
                [shiftId]: shift
            ]
        ]
    }
}

However, my current state setup is different:

state: {
    selectedShifts: {
        [employeeId]: {
            [shiftId]: shift
        }
    }
}

This difference in structure has made it challenging for me to manipulate and interact with the state as intended.

I have made an attempt to modify the reducer logic like this:

return {
    ...state,
    selectedShifts: {
      ...state.selectedShifts,
      [action.payload.employeeId]: {
        ...state.selectedShifts[action.payload.employeeId],
        [action.payload.shiftId]: action.payload[shift.shiftId]
      }
    }
  };

However, when I try to view the state after these changes, it appears like this:

state: {
    selectedShifts: {
        [action.payload.employeeId]: 
            [0]: {[action.payload.shiftId]: { shift }}
    }
}

I am encountering an issue where the {} symbols are not being replaced by [], resulting in an error message mentioning that a "," is expected.

Additionally, I would prefer for the index of the array to be based on the specific shift's id rather than numerical values such as [0], [1].

Is it feasible to achieve this desired structure? Would changing the index from numeric values to the actual shift's id pose any drawbacks?

Answer №1

Issues with array length may arise when data is added at numeric index points, causing problems with array methods like join, slice, indexOf, push, and splice.

var fruits = [];
fruits.push('banana', 'apple', 'peach');

console.log(fruits.length); // 3

If a property is set on a JavaScript array using a valid array index outside the current bounds of the array, the array's length property will be updated accordingly:

fruits[5] = 'mango';
console.log(fruits[5]); // 'mango'
console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
console.log(fruits.length); // 6

Updating or selecting state from an object involves different techniques compared to arrays. Utilizing Redux immutable patterns can help manage object updates effectively.

Consider structuring your state using object hashmaps rather than large arrays for improved performance.

To retrieve an array of selected user shifts for views, organize your state as follows:

state: {
    selectedShifts: {
        [employeeId]: {
            [shiftId]: shift
        }
    }
}

Retrieving shift information using NGRX selectors can streamline the process based on your specific requirements.

Ensure shifts are separated from selectedShifts in your state model for easier manipulation.

By customizing your state structure and selector functions, you can efficiently handle shift entities within your application.

For managing selectedShifts for employeeId, consider utilizing object hashes for faster access if dealing with large datasets.

Refer to additional resources for guidance on structuring complex state objects in Redux applications.

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

Managing unpredictable fields within a TypeScript interface Let me known if you need further assistance

Currently, I am developing a web application using Angular and encountered an issue with the JSON data returned by a service call. The problem arises when the mapped JSON contains an Object within one of the fields with unpredictable content. How can I han ...

Transforming a dynamic array into a new dynamic array (with a different data type) based on a property that can change over time

Explaining my process with the example of a REST api returning a list of objects, each needing a checkbox for selection and further processing. The api may be called multiple times for data refresh, utilizing Observables to handle selected values as an Obs ...

JSON definitions for Google Apps Scripts in TypeScript

Is there a way to obtain Typescript definitions for the raw JSON schema when creating a Google App Script with a cloud function, as outlined in the following link: https://developers.google.com/workspace/add-ons/alternate-runtimes-quickstart I've com ...

What causes a JSON error upon deleting a list in Replit?

Need assistance with deleting a specific index from a list stored in a json file The json file structure { "0": [ "0", "1", "2", "3" ] } The Python program import json with o ...

Transforming std::vector into a char* pointer

Currently, I am a C++ student who is undertaking a project that involves receiving and encoding a message using a simple cipher. The process begins by accepting each word as a string, converting it into a vector of characters, modifying each character, and ...

Calculate the sum of a parameter in an array when a specific condition is met

I have an array that needs to be processed. var arr = [ {'ResId':123,'ResVal':4,'Date':'11/03/2015'}, {'ResId':123,'ResVal':8,'Date':'11/03/2015'}, {'ResI ...

Exploring the variance between pointers in a two-dimensional array versus a one-dimensional array

Today I spent time practicing C code, focusing on arrays with return functions and pointers. I came across some confusing code snippets that left me wondering why they were written the way they were. First, there is a function that prints all elements of ...

Updating the page dynamically in React/Redux by making API calls based on user submissions

My current task involves calling an API with Redux, triggering the call based on a form submission. If the query is empty, it should return all lists; otherwise, it should only return lists that match the query. // List.tsx import React, { useEffect, useS ...

Guidelines for sorting a dataset according to the current UserID using angular2

Hello, I am working with a dataset where I need to filter the data based on my userID and display only that specific information in a list. Can someone assist me with this? TS: getDicomList() { this.service.getDicomList(params) .subscribe((res) ...

Difficulties setting up TypeScript in Laravel, alongside Vuejs and Inertia

Currently, my tech stack includes Laravel, Vue, and Inertia. However, I am looking to migrate everything to TypeScript, and I have encountered a roadblock that I can't seem to overcome. To aid me in this process, I referred to the following video tuto ...

Discovering the tiniest minimum values and storing them in an array

I am currently developing a method that will take a 2D array and determine the minimum value in each row. Once the minimum value is identified, I aim to store it in another array. However, despite creating the array, I keep encountering null values. This i ...

In search of a straightforward programming logic resolution

Currently, I am working on a project using CakePHP 2.x, and although my question is not related to syntax at the moment, I require assistance with a particular issue: Within my database, there exists a table called messages which contains a field named mo ...

Why does JSONResult automatically convert camelCase property names to lowercase?

Project Summary I am currently engaged in a project that involves: 1- Angular 6 2- Aspnet Core 2.1 Situation In my Angular code, I am making a GET request using the following snippet: let reqHeader = new HttpHeaders({ 'Content-Type': ' ...

What is the best way to sequentially populate combobox lists using arrays?

I am currently working on a userform that involves multiple combo boxes with lists sourced from dynamic arrays on a worksheet. While I have succeeded in filling one combobox with an array, I am seeking a more efficient way to fill each combobox with their ...

Error: { "message": "sqlite3_prepare_v2 error: token "876EL003" not recognized", "code": 5}

I am having trouble filtering the SQLite data with two conditions. I keep getting an unrecognized token error and I suspect that my query statement might be incorrect in the script. Could you please take a look and see if you can help me out? Thank you! ...

Testing a TypeScript function with Jest by mocking a function that is invoked from a separate file

In my code, there is a function called processCosts located in the file prepareStatement.ts. This function makes a call to another function named calculatePrice, which is imported from coreLogic.ts. Within my test file reports.integration.ts, I have impor ...

Best way to extract objects from an array by filtering based on the nested property value at nth level in JavaScript

Looking for a Solution: Is there an efficient method to filter out objects from an array based on a specific property value without using recursion? The Issue: While the recursive approach works for filtering, it struggles with performance due to a large ...

What is the best way to resize an array to a different length while preserving its close values in R programming?

I have two arrays with varying lengths value <- c(1,1,1,4,4,4,1,1,1) time <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) How can I adjust the length of the value array to match the length of the time array while preserving its approximate values? The a ...

How can I transfer checkbox selections from a dynamically generated table row to an Array in Vue?

After retrieving data from the Database, I pass it to the <tbody> element by iterating through its rows. These rows are enclosed within a child component and imported into the <tbody>: <template> <tr> <td> ...

What is the best way to arrange a two-dimensional table alphabetically?

I need assistance with organizing a double dimensional table. The table consists of letters on the first line, and below each letter are corresponding numbers. My goal is to arrange the letters alphabetically on the first line, while ensuring that the numb ...