Redux toolkit causing issues with triggering epics in Redux observable

I followed the documentation and implemented the following:

middleware/index.ts

import { combineEpics } from "redux-observable";
import userEpic from "./userEpic";

export const rootEpic = combineEpics(
    userEpic,
);

store.ts

import { configureStore } from "@reduxjs/toolkit";
import { createEpicMiddleware } from "redux-observable";
import { rootEpic } from "../middleware";
import userReducer from "./reducers/userSlice";

const rootReducer = {
  user: userReducer,
};
const epicMiddleware = createEpicMiddleware();

export const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) =>
  getDefaultMiddleware().concat(epicMiddleware),
});

epicMiddleware.run(rootEpic);

export type RootStateType = ReturnType<typeof store.getState>;
export type AppDispatchType = typeof store.dispatch;

export default store;

actions.ts

export const LOGIN_USER = "LOGIN_USER";
export const loginUser = () => {
  return {
    type: LOGIN_USER,
  } as const;
};
export type LoginUserAction = ReturnType<typeof loginUser>;

userEpic.ts (set up for testing purposes instead of API calls)

import { Action } from "@reduxjs/toolkit";
import { Observable } from "rxjs";
import { combineEpics, ofType } from "redux-observable";
import { LOGIN_USER } from "./actions";
import { map } from "rxjs/operators";
import { setUserData } from "../../redux/reducers/userSlice";

const fetchUserEpic = (action$: Observable<Action>) => {
  return action$.pipe(
    ofType(LOGIN_USER),
    map(() =>
      setUserData({
        id: 12,
        name: "test",
        surname: "test",
        username: "test",
        refreshToken: "test",
        accessToken: "test",
      })
    )
  );
};

export default combineEpics(fetchUserEpic);

userSlice.ts

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { FetchStatus } from "../../modules/types";
import { RootStateType } from "../store";

type UserType = {
  id: number;
  name: string;
  surname: string;
  username: string;
  refreshToken: string;
  accessToken: string;
};

type UserStateType = {
  user: UserType | null;
  userFetchStatus: FetchStatus;
};

const initialUserState: UserStateType = {
  user: null,
  userFetchStatus: FetchStatus.success,
};

export const userSlice = createSlice({
  name: "user",
  initialState: initialUserState,
  reducers: {
    setUserData: (state, action: PayloadAction<UserType>) => {
      state.user = action.payload;
      state.userFetchStatus = FetchStatus.success;
    },
    setUserFetchingStatus: (state, action: PayloadAction<FetchStatus>) => {
      state.userFetchStatus = action.payload;
    },
    clearUserData: () => {
      return initialUserState;
    },
  },
  extraReducers: (builder) => {
    builder.addDefaultCase((state) => {
      return state;
    });
  },
});

export const { setUserData, clearUserData } = userSlice.actions;

export const getUserData = (state: RootStateType) => state.user;

export default userSlice.reducer;

Attempting to console log data after triggering 'loginUser' action in component:

component.ts

const dispatch = useAppDispatch()
const user = useAppSelector(getUserData);
console.log(user)
<TouchableOpacity onPress={() => dispatch(loginUser)}>
//...

package.json

  "react-redux": "^8.0.1",
  "redux": "^4.2.0",
  "redux-observable": "^2.0.0"

The redux store does not seem to update; although 'loginUser' action is dispatched, 'ofType(LOGIN_USER)' does not capture it correctly. Attempted using 'filter(actionFunction.match),' as suggested elsewhere but received a deprecated error.

Answer №1

Ensure to invoke your action creator:

dispatch(loginUser()), not dispatch(loginUser).

In addition, it's highly recommended not to manually code that action creator - if you opt out of using createSlice, consider utilizing createAction instead.

export const loginUser = createAction('user/login')
.

Subsequently, you can also utilize filter(loginUser.match) along with it.

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

defining export paths for npm packages

I am embarking on creating my first series of npm packages to cater to a react-native environment. I want to ensure that the organization of these packages is impeccable and easily distinguishable through import statements on the client's end. Within ...

React - The Navbar is not visible and the screen appears blank

Attempting to set up a Navbar in a fresh React app (with React-Router-Dom) but encountering a strange issue where only a blank screen is displayed. From what I can tell and based on my research, everything seems to be set up correctly: App.js: import Reac ...

Mastering the use of Action.Submit in adaptive cards to simulate user input

I am trying to implement MessageFactory.SuggestedActions within my "welcomeCard" adaptive card. Essentially, in my adaptive card (welcome card), I have several buttons for the user to click on, each with an Action.Submit type. { "type" ...

Which is better for an uncomplicated app admin interface: Heroku or Firebase?

Looking for suggestions on whether Firebase or Heroku would be the better choice for creating a simple admin UI for a React Native photo app. I'm working on a basic React Native photo app for scientific purposes that involves capturing images, saving ...

Ways to evaluate a String that is thrown using Jest

I encountered a scenario where a function throws a string. Although Jest provides the toThrow matcher for testing functions that throw errors, it only works when an Error object is thrown. Is there a way to test if a string is thrown using Jest? The giv ...

Bringing in a service from a different module in NestJS

Having an issue trying to utilize the surveyService within the voteOptionRepository. When attempting to use the route, the console displays: TypeError: this.surveyService.getSurveyById is not a function Below is my SurveyModule setup: @Module({ im ...

Showcasing JSON information within a dropdown menu

In my project, I am working with two different JSON files named contacts and workers. Currently, I am using *ngFor to display the name of the contacts. In addition, I am also displaying the assigned workers for each contact in a dropdown, as shown below: ...

Place information from an input field into a specific row within a table

Utilizing Angular 4, I am developing a frontend application for a specific project. The interface features a table with three rows that need to be filled with data from an external source. https://i.stack.imgur.com/Dg576.png Upon clicking the "aggiungi p ...

Odd behavior of escape characters in Typescript

Looking for help with a query similar to the one referenced here. I am new to TypeScript and front end development. Currently using an Angular form to collect user input, which may contain regex. For example: The input from the form, stored in this.expr ...

Do arrow functions come highly recommended in Jasmine testing scenarios?

According to the mocha documentation, it is recommended to avoid using arrow functions. Does this same recommendation apply to Jasmine? I could not find any information on this topic in the Jasmine documentation. ...

Jasmine unit testing does not include coverage for if statements within functions

Currently, I am in the process of writing jasmine test cases for a specific block of code. While I have successfully covered the functions within the component, the if statements present within these functions remain untouched. Here are the if statements f ...

The Datepicker in MUI - React is unable to recognize the `renderInput` prop on a DOM element

I've been experimenting with the MUI version 5 DatePicker component. I followed the example provided in the MUI documentation's codesandbox demo. Here is how my component looks: const MonthPicker: FC = () => { const [value, setValue] = Rea ...

Organize and display a list of contacts alphabetically by the first letter of their

I have a list of contacts that I need help with. Despite searching on Stack Overflow, I couldn't find the answer. Can someone please assist? Thank you. export const rows = [ { id: 1, name: 'Snow', email: 'Jon', co ...

What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this: http://localhost:8080/api/v1/cardLimit 400 (Bad Request); JSON Object Example: public class GameLimit implements Serializable { private stati ...

Developing an Angular service to incorporate retry functionality for $http.get requests in Typescript

Looking to add offline support to my angular web-app, but struggling to get my simple retry function to function properly. My service code is as follows: constructor($http: ng.IHttpService, private $q: ng.IQService, private $interval: ng.IIntervalService, ...

The page is unable to find the 'backdrop' property because it is undefined

I'm currently using this code in my HTML page. In my angular module, I have imported all the necessary components. However, I keep encountering an error related to the backdrop. Can someone please assist me with this issue? I am unfamiliar with backdr ...

Encountering errors in Visual Studio when trying to work with node_modules directories that have a tsconfig

In my current project, there is a tsconfig.json file located in the root directory. Strangely, Visual Studio keeps throwing errors related to other instances of tsconfig.json found in different packages, as shown below: https://i.sstatic.net/T7Co2.png Ev ...

Struggling with TypeScript tests elusive to Jest

I'm encountering a strange error while attempting to write a jest test. TypeError: jest_1.it is not a function 9 | 10 | describe('Health check', () => { > 11 | it('GET works', async () => { Instead of displayi ...

Looking for ways to enhance the readability of JSON in your React-Typescript application?

After completing Stephen Grider's React and Typescript course on Udemy, I developed the JBook app. One of the challenges I encountered was ensuring that the content from a user's local file is displayed clearly in JBook. Currently, all content is ...

Filtering Typescript by property values of an interface that match its own values

Looking to extract specific types based on a given label Take a look at the code snippets below: interface TypeWithLabel { label: string; list: string; } interface A extends TypeWithLabel{ label: 'a'; list: '1' | &apo ...