What is the best way to standardize complex nested data within the ngrx/store?

Currently, I am utilizing ngrx/store with Angular 6. Within the store, there exists a deeply nested structure which I have concerns about in terms of its organization:

const state = [
  {
    aliases: ['alias1', 'alias2'],
    isRequired: false,
    isSensitive: false,
    name: 'Adress',
    timezoneId: 'UTC',
    children: []
  },
  {
    aliases: ['alias3', 'alias4'],
    isRequired: true,
    isSensitive: false,
    name: 'Phone',
    timezoneId: 'UTC-5',
    children: [
      {
        aliases: ['alias1', 'alias2'],
        isRequired: true,
        isSensitive: false,
        name: 'Sub-Phone',
        timezoneId: 'UTC-5',
        children: [
          {
            aliases: ['alias-phone1', 'alias-phone2'],
            isRequired: false,
            isSensitive: true,
            name: 'Sub-Sub-Phone',
            timezoneId: 'UTC',
            children: []
          }
        ]
      }
    ]
  }
]

The issue arises from the fact that the property name acts as an identifier and must be unique at the same level, but can repeat within the child elements. For instance, both Sub-Phone and Sub-Sub-Phone could be labeled as Phone. What approach should I take to effectively organize this type of structure in the store so that it remains flexible for future modifications? Currently, if I wish to modify name: 'Phone', it necessitates updating the entire object including all its descendants within the reducer function. How can I normalize this data?

Answer №1

If you're looking to create a well-organized state structure, consider following this helpful guide on normalizing state shape. Avoid nesting data excessively. Instead, create an identifier for entities and another one for their relationships (such as children in your case). To illustrate, I've put together a basic example state for you:

const state = {
  objects: {
    id: ['Address', 'Phone', 'Sub-Phone', 'Sub-Sub-Phone'],
    entities: {
      'Address': {
        isRequired: false,
        isSensitive: false,
        timezoneId: 'UTC'
      },
      'Phone': {
        isRequired: true,
        isSensitive: false,
        timezoneId: 'UTC-5'
      },
      'Sub-Phone': {
        isRequired: true,
        isSensitive: false,
        timezoneId: 'UTC-5',
      },
      'Sub-Sub-Phone': {
        isRequired: false,
        isSensitive: true,
        timezoneId: 'UTC',
      }
    }
  },
  children: {
    'Address': [],
    'Phone': ['Sub-Phone'],
    'Sub-Phone': ['Sub-Sub-Phone']
  }
}

Note the two levels within the state: objects and children. The objects section contains identifiers and corresponding entity details. Meanwhile, the children section includes arrays of child elements for each object key. In my example, there's only one child per array, but you can expand it like this:

'Phone': '['Sub-Phone', 'Sub-Phone2', 'Sub-Phone3']

Answer №2

One way to handle data normalization is by incorporating it into the server implementation if you have access. However, in most cases, you may need to normalize the state on the client side using a library like normalizr.

If you're interested in learning more about this topic, there are various articles available such as this one on Hackernoon.

Answer №3

Utilizing @ngrx/entity is a fantastic method for organizing your store in a standardized way. Take a look at the comprehensive @ngrx/entity ReadMe.

In addition, it features a robust entity adapter and selectors to enhance functionality.

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

Encountering a issue when trying to render an image retrieved from an API in Next JS

I encountered an issue where I am unable to retrieve the image from the API. Strangely, it works fine with the img tag but throws an error when switching to the NextJS Image tag. import React, { useState, useEffect } from "react"; import ...

Using Angular Typescript with UWP causes limitations in accessing C# WinRT component classes

Currently, I am working on a UWP application built with Angular5 and I would like to incorporate Windows Runtime Component(Universal) classes into the application to access data from a table. import { Component,OnInit } from '@angular/core'; @C ...

Leveraging the power of `useDispatch` and `connect`

When it comes to dispatching actions in react-redux, I've noticed that both useDispatch and connect are available options. However, I'm curious about whether I can exclusively use useDispatch to handle store data throughout my entire react app. A ...

What steps should I follow to ensure that this table can be sorted efficiently?

I could use some help with this problem. I am new to ReactJS and struggling to implement table sorting based on the clicked column. Do I need to add a class for this? Any assistance would be greatly appreciated. function CreateGradeTable(props) { r ...

The release of the Angular App within a webjar is causing problems relating to the baseHref

Currently, I am looking to package my Angular frontend in a webjar so that it can be easily imported via Maven into any Java backend. Successful in this task, I now have a Spring Boot backend with an application.properties file showing: server.servlet.cont ...

Ensure that only one Accordion in React MUI is always open

import React, { useState } from "react"; import { Accordion, AccordionDetails, AccordionSummary, Typography } from "@mui/material"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; export default function ...

What are the best ways to make this date more visually appealing and easy to understand?

Hey there! So I have a date that looks like this: 2022-06-28T17:09:00.922108+01:00 I'm trying to make it more readable, but unfortunately, when I attempted using moment-js in my javascript/react project, it threw an error stating "invalid format". ...

While working with Ngrx/effects, an error with code TS2345 occurred. The error message stated that the argument is of type 'Product[]', which cannot be assigned to a parameter of type

When I compile my code, I encounter the following issue (despite not finding any errors in the browser console and the application functioning properly). An error occurs in src/app/services/product.service.ts(15,9): The type 'Observable<Product> ...

Integrating domain name into a post request using React

Currently, I have a frontend (react, Node.js) and a backend Springboot hosted on the same remote hosting service at . The frontend and backend are placed in different environments but function well individually. I connected my frontend to a domain and up ...

"ReactJS and Express: Building versatile applications for the public and administrative use

Currently, I am in the process of developing a single page application using ReactJS with a separate admin SPA. After going through 4-5 tutorials to establish the basic structure, I find myself at a point where I need guidance on how to create the admin se ...

Error: Material-UI prop type validation failed - Please specify either `children`, `image`, `src`, or `component` prop

Despite having an image prop in CardMedia, I kept encountering this error. Here is a snippet of the code: Error description: const Post = ({ post, setter }) => { const classes = useStyles(); return( <Card className={classes.card} ...

The ES6 method of binding click handlers with parameters in React

After reading numerous articles on the usage of () => {} syntax, binding in the constructor, and binding in the props, I have come to understand that binding this can be performance-intensive. Furthermore, automatic binding with arrow functions incurs a ...

Unable to alter fxFlex property within Component using "setAttribute('fxFlex', '25%')" does not function properly in Angular 6

Currently, I am utilizing the flexLayout module to create responsive divs in my Angular application. You can find more information about flexLayout at https://github.com/angular/flex-layout and also at https://alligator.io/angular/flex-layout/. const nav ...

What is the solution in React when a string needs to be converted into an object?

Attempting to use an onClick event in react, I am trying to add a new object (dictionary) with the id of the clicked object as a key (prevId). However, when the first object is created without a value for that parameter, I set a default value of '0&a ...

Creating a redux store with an object using typescript: A step-by-step guide

Having recently started using Redux and Typescript, I'm encountering an error where the store is refusing to accept the reducer when working with objects. let store = createStore(counter); //error on counter Could this be due to an incorrect type set ...

Challenges with character encoding in NextJS

I am currently dealing with a line of code that creates a dynamic route. <Link href={`/bundeslander/${urlName}`} ><div className=" text-blue-400">{state.name}</div></Link> The variable urlName is generated by fetching dat ...

Why does the same error keep popping up every time I attempt to install my React application?

I am new to React and feeling frustrated as I keep encountering the same error repeatedly. I have tried three different codes individually: npx create-react-app myapp npm init react-app myapp npm install -g create-react-app followed by create-react- ...

Angular2 - leveraging root-relative imports

Having trouble with imports in angular2/typescript? Want to use paths relative to the project root like 'app/components/calendar', but currently stuck using something like this: //app/views/order/order-view.ts import {Calendar} from '../../ ...

Do you need to include 'passHref' when using NextJS <Link> with Semantic UI React as the child component?

After diving into the nextjs docs, I came across a section here that discusses: If the child component of Link is a function component, it's necessary to use passHref and wrap the component in React.forwardRef: As someone new to Semantic UI React, ...

Storing a Material-UI component in a variable and referencing it later on in a React application

I am trying to save a Material-UI (MUI) icon component in a variable, like this: item.icon = <FilterListIcon />; Later on, in other components, I want to use it like this: <ListItem button key={item.text} onClick={item.onClick}> {item.icon ...