Invoke an ActionCreator within a different ActionCreator

Calling an ActionCreator from another file is proving to be a challenge...

The products.ts file contains the ActionCreators and Reducers for Products...

import { setStock } from './Store.ts';
//....
export const addProduct = (product: IProduct) => async (
  dispatch: Dispatch,
  getState: () => IState,
  { auth }: IServices
) => {
    dispatch(fetchStart());

    const response = await Axios.post('/api/products', product)

    const productInfo = response.data as IDataProduct

    // # Needing to call SetStock() 
    // # [Try 1] Attempting to Call
    setStock(productInfo)

    // # [Try 2] Attempting to Call
    // return (dispatch2: any) => {
      //  dispatch2(
         //setStock(producto._id)
        //  )
    // }

    dispatch(fetchSucess(productInfo))
};

I tried using try 2 as per an example I saw, but it didn't work. The first try didn't produce desired results either.

The stores.ts file contains the following...

export const setStock = (product: any) => async (
  dispatch: Dispatch,
  getState: () => any,
  { auth, db }: IServices
) => {
  console.log('INIT SETSTOCKACTIONCREATOR....')
  dispatch(fetchStart());
  try {
    const ref = db.collection("stores").doc(storeId);    
    await ref.update({ [product._id]: product.newStock });

    dispatch(updateSucess({ _id: storeId, stock: product.newStock, productId: product.productId }));

  } catch (error) {    
    dispatch(fetchError(error));
  }
};

Encountering an issue when trying to do Dispatch(setStock(productInfo)), with TypeScript throwing an error message:

Argument of type '(dispatch: Dispatch, getState: () => any, { auth, db }: IServices) => Promise' is not assignable to parameter of type 'AnyAction'.

Property 'type' is missing in type '(dispatch: Dispatch, getState: () => any, { auth, db }: IServices) => Promise' but required in type 'AnyAction'

Answer №1

To trigger the setStock action, simply use dispatch(setStock(producto._id)) in a manner that is similar to how you call fetchStart

export const addProduct = (product: IProduct) => async (
  dispatch: ThunkAction<Promise<void>, {}, {}, AnyAction>,
  getState: () => IState,
  { auth }: IServices
) => {
    dispatch(fetchStart());

    const response = await Axios.post('/api/products', product)

    const producto = response.data as IDataProduct

    dispatch(setStock(producto._id))


    dispatch(fetchSucess(producto))
};

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

Set the Checkbox selections by utilizing the array values in the MUI DataGrid

In my MUI Datagrid, I have 2 columns for ID and City Name. There are only 3 cities represented in the table. Within a citizen object like this: const userMockup = { id: 1, name: "Citizen 1", cities: [1, 2], isAlive: true }; The cities ar ...

What is the best way to pass the value of a button to a different react component

Hey there! I'm currently working on a form component that includes a button array. I've added icons to the buttons using the value attribute, like so: <button value={'admin'} onClick={(e)=> handleClick(e.target.value)}> & ...

Showcasing or concealing.JSON data depending on the selected item in a React and MaterialUI application

Looking to enhance the user experience, I am developing a dynamic FAQ section sourced from a JSON file containing an array of objects with 'Question' and 'Answer'. https://i.stack.imgur.com/mljpm.png The functionality is such that click ...

The build process was unsuccessful due to an error stating: "Unable to compile - Unable to read property 'toLowerCase' of an undefined value

Whenever I run npm run build in my create-react-app project, it fails to compile and shows me the error message Cannot read property 'toLowerCase' of undefined. I have examined my code and realized that I do not use toLowerCase anywhere. The onl ...

Struggling with integrating Material UI radio buttons into Formik Part Two

Some time ago, I sought help on integrating radio buttons with Material UI and Formik in this thread: Cannot get Material UI radio buttons to work with Formik. Despite receiving a solution, it unfortunately didn't resolve the issue in our specific app ...

What is the best way to transfer the information from my MYSQL database into a JSON array?

After setting up a MySQL database that I can query using ExpressJS and NodeJS, I found the following data structure: id: 1 username: 'someUsername' email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9fedfef1f ...

What causes observables stream to be cancelled or stopped by my HTTP request?

I am facing an issue with adding a new property called Blobs to each application in an array of applications. I need to make a separate HTTP request to fetch Blobs for each application using the switchMap operator. However, the problem is that only the las ...

Axios - Error: Promise Rejected - The request was unsuccessful with a 500 status code

The Axios post request in my code for adding new articles is not going through, and I am encountering an error: Failed to load resource: the server responded with a status of 500 (Internal Server Error) createError.js:17 Uncaught (in promise) Error: Requ ...

Tips for sending an email to an address from a user input field in React.js/Express.js

I am currently developing an email application that allows users to send emails to any recipient of their choice. The challenge I'm facing is that I need a way to send emails to user-specified email addresses without requiring passwords or user.id det ...

Error starting the Heroku web service: start script failed

Encountering the following issue: Failed at the [email protected] start script. while trying to deploy an express + react application. The problem seems to be related to concurrently on Heroku. https://i.stack.imgur.com/BEuZL.png Any suggestions ...

"Padding has not been recognized as a valid input value

I'm struggling with getting padding to be accepted by the browser when I style a card using Material-UI. const useStyles = makeStyles((theme) => ({ cardGrid: { padding: '20px auto' }, })) Unfortunately, the browser is not recogni ...

Reactive DevExpress introduces a unique Custom Paging Panel that enhances user

I am looking to customize my Paging Panel in a unique way: Instead of displaying the options for Rows per page as a select dropdown, I want to show them as buttons; I do not want to show the numbers of rows that are currently being displayed; I may want t ...

What is the best way to showcase text formatting applied in Strapi's WYSIWYG editor in NextJS's user interface?

I'm a beginner with Next JS and Strapi CMS. Trying to figure out how to transfer styling from the backend admin panel in Strapi to the UI in NextJS. Is there a way to display the formatted text created in Strapi's WYSIWYG editor on the frontend ...

Implementing rxjs switch between multiple observables

As I work with 2 observables, my goal is to retrieve a value from Observable1, then disregard it and only anticipate a value coming from Observable2. After that, repeat the process by getting a value from Observable1 once more, and so on. I am exploring w ...

What could be the reason for the lack of styling on the select element when using PaperProps in the MenuProps of my Select component?

I've been struggling to remove the white padding in this select box for a while now. I've tried countless variations and places to tweak the CSS with no success. Any suggestions on how to make it disappear? The project is using MUI 5, and I even ...

I keep encountering an error when trying to import an image from the asset folder in Next.js

After successfully creating a React app, I encountered an error when trying to incorporate all the files into a Shopify app where Next.js is present. import React, {createContext, useState} from "react"; import bag from &quo ...

Having trouble getting card animations to slide down using React Spring

I am currently learning React and attempting to create a slide-down animation for my div element using react-spring. However, I am facing an issue where the slide-down effect is not functioning as expected even though I followed a tutorial for implementati ...

Interacting with Material-UI GridTile: Understanding Touch Events

I am currently utilizing the library material-ui and have a GridList containing GridTiles that can respond to two distinct touch events. When a user touches the tile, they should navigate to another route, and when they touch the 'actionIcon', it ...

Issue with Flex display not being applied within Material UI Grid Item

I am attempting to position an element at the end of a Grid Item (horizontally). In order to achieve this, I am enclosing my component in the following div: Here is the complete code snippet: <Grid container spacing={8} alignItems={'stretch' ...