When the state is updated, the Observable fails to retrieve the value from the store

My goal is to update the Observable by connecting it to the store, but I encountered an issue where it didn't get updated when the store received a new value:

Within my component, I have declared 'tasks' as an Observable:

tasks$: Observable<any> = this.store.pipe(select(state => {
    console.log('state', state);
    return state;
})); // This works and retrieves the full state

tasks$: Observable<TaskModel[] | undefined> = this.store.select(selectTasks); 
// However, this does not work, as it cannot select tasks from the state

Reducer:

const tasksReducers = createReducer(
  initialState,
  on(getTasks, (state) => ({...state, isLoading: true})),
  on(getTasksSuccess, (state, result) => ({...state, tasks: result.tasks, isLoading: false}))
);

Selector:

export const selectTasksState = (state: TasksState) => state;

export const selectTasks = createSelector(
  selectTasksState,
  (state: TasksState) => state.tasks
);

Effect:

getTasks$ = createEffect(() =>
    this.actions$.pipe(
      ofType(getTasks),
      exhaustMap(action => this.tasksService.getTasks().pipe(
        tap(response => console.log('response', response)),
        map(tasks => getTasksSuccess({tasks})),
        catchError((error: any) => of(getTasksFailure(error)))
      ))
    )
  );

Actions:

export const getTasks = createAction(TasksActionTypes.GET_TASKS);
export const getTasksSuccess = createAction(TasksActionTypes.GET_TASKS_SUCCESS, props<{tasks: TaskModel[]}>());
export const getTasksFailure = createAction(TasksActionTypes.GET_TASKS_FAILURE, props<{message: string}>());

State:

export interface TasksState {
  tasks?: TaskModel[],
  isLoading?: boolean;
  isLoadingSuccess?: boolean;
  isLoadingFailure?: boolean;
}

It seems that the selector is not recognizing the state change, thus the update is not being reflected. I have verified that a new object is created in the reducer, so I am unsure of where the issue lies.

Answer №1

To achieve the desired result, implement the following steps in your TypeScript file:

selectedData: any;

ngOnInit(): void {
    this.selectedStoreData$ = this.store.select(selectorStoreData);
    
    this.selectedStoreData$.subscribe((data: any) => {
      if (data) {
        this.selectedData= data;
      }
    });
 }

By following the code above, the data will be subscribed and stored in the variable selectedData.

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

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

npm encountered an error while trying to update Angular 4

Looking to update Angular2 to Angular 4 and encountering an issue with the following command: npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular ...

Problem with ngStyle: Error indicating that the expected '}' is missing

I encountered an error in the Chrome console when trying to interpret the code below: <div [ngStyle]="{'width': '100%'; 'height': '100%'; 'background-size': 'cover'; 'background-repeat&ap ...

Navigate to the previous page

What is the best way to navigate back to the last page in Angular 2? Can it be done like this? this._router.navigate(LASTPAGE); For instance, if page C includes a Go Back button, From Page A to Page C, clicking it will take you back to Page A. Fro ...

Guide on how to prevent click events when a checkbox is not selected in Angular 2

A click event is being used on a ul element with a checkbox below it. When the checkbox is checked, the list should be enabled and the click event should work. If the checkbox is unchecked, the list should be disabled and the click event should not work. ...

Tips on properly declaring props in Typescript when a parent component is passing props down to its children componentsуж

When a parent component clones its children to pass props to them, how can we specify the type of props for the children? I'm encountering an issue because injectedProps is expected in the Child component const Parent: React.SFC<ParentProps> = ...

One way to organize data from my API is by sorting it based on two date conditions. If one of those conditions is missing, the data should be placed at the beginning of the list

I am facing a challenge with sorting the return from my API based on the StartDate. However, I need to implement a validation where if there is no FinalDate provided, the data should appear at the first index of the result. StartDate: "2004-06-04" ...

Request for /Account after Keycloak token request in Angular app

I have been working on an Angular and Keycloak project. I followed a tutorial that helped me integrate Keycloak into Angular, which can be found here: https://www.npmjs.com/package/keycloak-angular My public client is able to request a token, but when it ...

Serve both .ts and .js files to the browser using RequireJs

In my ASP.NET Core Project, the following files are present: greet.ts export class WelcomMesssage { name: string; constructor(name: string) { this.name = name; } say(): void { console.log("Welcome " + this.name); } } GreetExample.ts import * as ...

Is it possible to send a JSON object to a RESTful API in Angular 2+ without relying on cookies?

Struggling to send a json type object to the rest service in an (angular2+ springMvc + java) web project. It's proving to be quite challenging, and on top of that, I'm unable to utilize cookies too. ...

NX nest application: accessing environment variables from the distribution directory

I've organized my project structure like this: https://i.sstatic.net/WRKCI.png Using nx with nest. In the app.module.ts file, I've set up the ConfigModule to read the .env file based on the NODE_ENV variable, which is then used to connect to Mo ...

Most Effective Approach for Handling Multiple Fetch Requests Concurrently using Async-Await in TypeScript?

I am currently exploring the idea of making multiple API calls simultaneously by utilizing multiple fetch requests within an await Promise.all block, as shown below: const responseData = await Promise.all([ fetch( DASHBOARDS_API + "getGoal ...

Volar and vue-tsc are producing conflicting TypeScript error messages

During the development of my project using Vite, Vue 3, and TypeScript, I have set up vue-tsc to run in watch mode. I am utilizing VS Code along with Volar. This setup has been helpful as it displays all TypeScript errors in the console as expected, but I ...

Typescript custom react hook - toggling with useToggle

I developed a custom hook to toggle boolean values: import { useState } from 'react'; export function useToggle(initialValue: boolean) { const [value, setValue] = useState<boolean>(initialValue); const toggleValue = () => setValue ...

Is it possible for the like button to display specific information when clicked?

When working with a looping structure in Ionic and Angular, which includes post content such as text, photos, and videos, I am encountering an issue with selecting specific data when clicking on the like button. How can I ensure that only the data associat ...

Utilizing localstorage data in angular 2: A comprehensive guide

Is there a way to utilize data stored in localstorage for another component? This is what the localstorage service looks like: localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success, res: res.data })); I am inte ...

The angular2-markdown module encounters errors

I am currently working on implementing a markdown editor in a form within my Angular2 project. To achieve this, I have installed the angular2-markdown module. However, I encountered an error when trying to use it, specifically: "marked" is not a function. ...

The index type '{id:number, name:string}' is not compatible for use

I am attempting to generate mock data using a custom model type that I have created. Model export class CategoryModel { /** * Properties */ public id : number; public name : string; /** * Getters */ get Id():number{ return this.id; ...

angular overlapping collapsing

Currently, I am developing a chat board application where users can leave comments under each post. I am in the process of creating a button that will collapse all the comments for better visibility, especially as they continue to grow. <div id="collap ...

After being awaited recursively, the resolved promise does not perform any actions

When working with the Twitter API, I need to make recursive method calls to retrieve tweets since each request only returns a maximum of 100 tweets. The process is straightforward: Call the function and await it Make an HTTP request and await that If the ...