When there is a change in the signal property within a Signal Store, data will be loaded accordingly

Within my application, I am utilizing a signal store to effectively manage the state pertaining to projects and sites. The current implementation is as follows:

interface State {
  selectedProject: Project | null,
  selectedSite: Site | null,

  projects: Project[],
  sites: Site[],
}

export const Store = signalStore(
  withState<State>({
    selectedProject: null,
    selectedSite: null,

    projects: [],
    sites: []
  }),

  withMethods(state => {
    const sitesService = inject(SitesService);
    const projectsService = inject(ProjectsService);

    return {
      loadSites: async () => {
        const sites = await sitesService.getSites();
        patchState(state, { sites });
      },
      loadProjectsBySiteId: async (siteId: number) => {
        const projects = await projectsService.getProjectsBySiteId(siteId);
        patchState(state, { projects });
      },
      setSelectedSite: (selectedSite: Site) => {
        patchState(state, { selectedSite, selectedProject: null });
      },
      setSelectedProject: (selectedProject: Project) => {
        patchState(state, { selectedProject });
      }
    };
  }),

  withHooks({
    onInit({ loadSites }) {
      loadSites();
    }
  })
);

My goal is to automatically load the projects whenever there is a change in the selectedSite. However, I am uncertain about the most effective approach to achieve this within the setup of my signal store.

I am contemplating between utilizing the withComputed feature or implementing the functionality within the setter setSelectedSite (to trigger a fetch or similar action).

What would be the best practice for loading projects based on the change in selectedSite in this scenario?

Answer №1

Here is my proposed solution to the problem at hand. I'm a bit uncertain if updating a store value within an effect could potentially lead to complications...

usingHooks({
onInitialLoad({ fetchSites, currentSite, fetchProjectsBySiteId }) {
  fetchSites();
  effect(() => {
    const currentSiteId = currentSite()?.id;
    if(currentSiteId) {
      fetchProjectsBySiteId(currentSiteId);
    }
  }, { allowWriteSignals: true });
}

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

Display a custom error message containing a string in an Angular error alert

How can I extract a specific string from an error message? I'm trying to retrieve the phrase "Bad Request" from this particular error message "400 - Bad Request URL: put: Message: Http failure response for : 400 Bad Request Details: "Bad Request ...

Issue with nestjs build due to ts-loader module in dev-dependency

I've encountered a Module Error with ts-loader during a docker build ERROR [6/6] RUN nest build 3.9s ------ > [6/6] RUN ...

What is the correct method to obtain a reference to the host directive within a ControlValueAccessor implementation?

Is there a proper way to connect two directives, or a directive to a component (which is a directive as well) in angular2 following the "angular way of writing code"? Given the limited documentation on angular2, any insights or references on this topic wo ...

Problems encountered with operating the Bootstrap burger menu

After following the Bootstrap navbar documentation and implementing the code in my bs-navbar.component.html file, I encountered an issue with the hamburger menu. Despite everything being set up correctly, clicking on the hamburger icon did not display the ...

Exploring Angular's ViewContainerRef with Directive Testing Simulation

When utilizing a directive for Dynamic Component Loading and injecting ViewContainerRef: import { Directive, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[fooHost]' }) export class FooDirective { constructor(pu ...

This error occurs because the argument type 'AsyncThunkAction<any, void, {}>' cannot be assigned to a parameter of type 'AnyAction'

I encountered an error that I couldn't find a solution for on Stack Overflow The argument of type 'AsyncThunkAction<any, void, {}>' is not compatible with the parameter of type 'AnyAction'. <MenuItem onClick={() =&g ...

Is there a way to convert TSX source code into regular TS code?

I am in need of the functionality offered by @babel/plugin-transform-react-jsx, while keeping all types, TypeScript language features, ESNext syntax, comments, etc. I aim to convert TypeScript XML-formatted code into plain TypeScript using a specific JSX ...

Allow exclusively certain type to pass through the function

Is it possible to receive an error message from the function in the following example? I have included comments at a relevant spot in the code below: interface Pos { x: number, y: number, } function doSome(pos: Pos) { return pos.x + pos.y } let p ...

Creating a Session Timeout feature for Ionic/Angular that includes resetting the timer with each new user interaction

Having trouble implementing a session timeout feature in my code. I need the timer to reset whenever a user interacts with the function. Can't figure out how to integrate similar code like the one provided as an example on Stack Overflow. This is the ...

Issue: The 'draggable' property is not found on the 'JQuery<HTMLElement>' type

When using Angular 2 and Typescript in conjunction with JQuery and JQueryUI, I encountered the following error: Property 'draggable' does not exist on type 'JQuery<HTMLElement>' I am aware that .draggable() is a function that rel ...

Issues arise after upgrading Node and npm, causing an inability to execute any npm command

Following an upgrade to the latest Node and npm version, I encounter an error when attempting any npm command: C:\Users\...>npm doctor TypeError: Cannot read property 'prefix' of undefined at parseField (C:\Users&bs ...

Angular 6 Subscription Service Does Not Trigger Data Sharing Events

Is there a way to set a value in one component (Component A) and then receive that value in another component (Component B), even if these two components are not directly connected as parent and child? To tackle this issue, I decided to implement a Shared ...

Securing Your Angular 6 Application with Authentication

As a beginner in web development with Angular, I have encountered a lot of discussions on the topic of using JWT or cookies for authentication. I am curious to know what method you are using for authentication with Angular 6, and if you are using JWT, ho ...

Partial argument cannot be assigned to the specified parameter type

I'm attempting to update a partial property of an interface in TypeScript like this: interface details{ name: string, phonenumber: number, IsActive: boolean } let pDt: Partial<details> = {IsActive: false}; However, when I try to pass it ...

What is the best way to ensure that all function parameters using a shared generic tuple type have a consistent length?

Understanding that [number, number] | [number] is an extension of [number, ...number[]] is logical, but I'm curious if there's a method to enforce the length of tuples based on the initial parameter so that the second tuple must match that same l ...

Could an OpaqueToken be assigned using an observable?

I am attempting to establish an opaque token in the providers using an observable. The purpose behind this is that I am retrieving the value through the Http provider (from an external JSON file). This is my current approach: { provide: SOME_ ...

Reducing code size in webpack during the transition from Angular2 to Angular4

After upgrading our web app from Angular 2.1.1 to 4.1.2, we implemented Webpack 2 for building and development. While everything is functioning properly, we have noticed that the code size in our final build remains unchanged. Should we consider configuri ...

"Utilize Angular's functionality to include labels for checkboxes generated using *ngFor directive

I am currently working with Angular 5 My goal is to generate multiple checkboxes using the code below and provide them with labels <input type="checkbox" *ngFor = "let v of options[0].options" [value]="1" [name] = "1"> Typically, when working with ...

The type FormGroup<any> lacks the controls and registerControl properties compared to AbstractControl<any>

I've been developing a reactive nested form inspired by this YouTube tutorial - https://www.youtube.com/watch?v=DEuTcG8DxUI Overall, everything is working fine, except for the following error - https://i.sstatic.net/bZHPV.png Below are my files. ho ...

Value of type 'string' cannot be assigned to type '{ model: { nodes: []; links: []; }; }'

I am a beginner in TypeScript and I have added types to my project. However, I am encountering an error with one of the types related to the graph: Type 'string' is not assignable to type '{ model: { nodes: []; links: []; }; }'.ts(2322) ...