Untitled

mail@pastecode.io avatar
unknown
typescript
a year ago
1.7 kB
4
Indexable
Never
***********Reducer:

import { createReducer, createAction } from '@reduxjs/toolkit';
import { setUser, getUser } from '../actions/UserActions';

const initialState = {
  user: null,
};

const userReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(setUser, (state: any, action) => {
      state.user = action.payload.user;
    })
    .addCase(getUser, (state: any, action) => {
      return state.user
    });
});

export default userReducer;

***********Store: 

import userReducer from "./reducers/TaskGroupReducer";
import { configureStore } from "@reduxjs/toolkit";
import logger from 'redux-logger'

class Store {
  private static instance: any;
  private store: any;

  private constructor() {
    this.store = configureStore({
      reducer: { 
        user: userReducer
      },
      middleware: [logger],
    });
  }

  public static getInstance(): any {
    if (!Store.instance) {
      Store.instance = new Store();
    }
    return Store.instance.store;
  }
}

const store = Store.getInstance();
export default store;

***********Actions 

import { createAction } from '@reduxjs/toolkit'
import { User } from '../../../model/UserDTO';

export const getUser = createAction('user/get');
export const setUser = createAction('user/set', (user: User) => {
    return {
        payload: {
            user: user
        }
    }
});

**********UserDTO: 

export interface User {
    email: string
}

***********Test
const dispatch = useDispatch();

const b = () => {
  const user = useSelector((state) => console.log(state) );
  console.log(user);
}

const a = () => {
    let a: User = {email}
    dispatch(setUser(a));
}