NgRx does not use effects, how to store data in the store

In ngrx, if you don't want to use @Effect to handle side effects (such as asynchronous operations), you can directly store data in the reducer. Here are the general steps on how to do this:

Create an Action class: First, create an Action class to describe the operation you want to perform, such as adding data to the store.

// my-actions.ts
import {
    
     createAction, props } from '@ngrx/store';

export const addData = createAction('[My Component] Add Data', props<{
      
       data: any }>());

Update the reducer: In your reducer, add a case that handles the Action to store the data in the store.

// my-reducer.ts
import {
    
     createReducer, on } from '@ngrx/store';
import {
    
     addData } from './my-actions';

export const initialState = {
    
    
  data: null,
};

const myReducer = createReducer(
  initialState,
  on(addData, (state, {
    
     data }) => {
    
    
    return {
    
     ...state, data };
  })
);

export function reducer(state, action) {
    
    
  return myReducer(state, action);
}

Dispatch Action in your component: In your component, dispatch the Action defined above when you want to add data to the store.

// my-component.ts
import {
    
     Component } from '@angular/core';
import {
    
     Store } from '@ngrx/store';
import {
    
     addData } from './my-actions';

@Component({
    
    
  selector: 'app-my-component',
  template: `
    <button (click)="addDataToStore()">Add Data to Store</button>
  `,
})
export class MyComponent {
    
    
  constructor(private store: Store) {
    
    }

  addDataToStore() {
    
    
    const dataToAdd = // 数据的来源,例如从表单中获取
    this.store.dispatch(addData({
    
     data: dataToAdd }));
  }
}

This way, when you click the "Add Data to Store" button, the addData Action will be dispatched and the reducer will update the data in the store based on the Action.

Here is a simple example showing how to store data in ngrx without using @Effect. If you need to perform more complex operations, such as getting data from the server or handling other asynchronous operations, you may want to consider using @Effect to handle these side effects.

Guess you like

Origin blog.csdn.net/weixin_43160662/article/details/132867094