Skip to content

Create Store service for updating the UI automatically #20

@DavMunHer

Description

@DavMunHer

Given all the refactors made in the PR #19 , when we start implementing the backend API, we will be needing a new service (Store Service) that will consume from the project api service.

Example of code implementation (this is just an example and will not work in the project, since our entities are a bit different):

@Injectable({ providedIn: 'root' })
export class ProjectStore {
  private _project = signal<Project | null>(null);
  private _sections = signal<Record<string, Section>>({});
  private _tasks = signal<Record<string, Task>>({});

  readonly projectView = computed<ProjectView | null>(() => {
    const project = this._project();
    if (!project) return null;

    return {
      id: project.id,
      name: project.name,
      sections: project.sectionIds
        .map(id => this._sections()[id])
        .filter(Boolean)
        .map(section => ({
          id: section.id,
          title: section.title,
          tasks: section.taskIds
            .map(id => this._tasks()[id])
            .filter(Boolean)
            .map(task => ({
              id: task.id,
              title: task.title,
              completed: task.completed,
            })),
        })),
    };
  });

  constructor(private projectApi: ProjectApi) {}

  loadProject(projectId: string) {
    this.projectApi.loadProject(projectId).subscribe(({ project, sections, tasks }) => {
      this._project.set(project);
      this._sections.set(Object.fromEntries(sections.map(s => [s.id, s])));
      this._tasks.set(Object.fromEntries(tasks.map(t => [t.id, t])));
    });
  }
}

For the component itself:

export class ProjectViewComponent implements OnInit {
  readonly project = this.projectStore.projectView;

  constructor(private projectStore: ProjectStore) {}

  ngOnInit() {
    this.projectStore.loadProject('123'); // trigger HTTP request
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions