Activate a function upon an event using react-redux

Implementing a modal form with an ajax request using react, redux, and react-redux has been my current project.

In my understanding, react-redux allows you to :

  • display data from the redux store in your component
  • dispatch an event from the container to redux

I have also integrated redux-saga to manage Ajax requests triggered by redux.

However, I am facing a challenge on how to perform an action (e.g. close the modal form) when a specific event is triggered from Redux.

Below is an example of code snippet:

class MyFormDialog extends React.Component {
    state = {
        open: false,
    };


    handleOpen = () => {
        this.setState({open: true});
    };

    handleClose = () => {
        this.setState({open: false});
    };

    render() {
        const actions = [
            <FlatButton
                label="Cancel"
                onTouchTap={this.handleClose}
            />,
            <FlatButton
                label="Submit"
                onTouchTap={this.props.ajaxRequest}
            />,
        ];

        return (
            <div>
                <MenuItem primaryText="Make a request"  onTouchTap={this.handleOpen}/>
                <Dialog
                    title="Make a request"
                    actions={actions}
                    modal={true}
                    open={this.state.open}
                    onRequestClose={this.handleClose} />
            </div>
        );
    }
}

const mapStateToProps = (state, ownProps) => {
    return {
        loading: state.isLoading,
        success: state.success,
        error: state.error,
    }
};

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        ajaxRequest: (url, tags) => {
            dispatch({type: "AJAX_REQUESTED"})
        },
    }
};

const ConnectedMyFormDialog = connect(
    mapStateToProps,
    mapDispatchToProps
)(MyFormDialog );

export default ConnectedMyFormDialog ;

The reducers are structured as follows:

  • isLoading = true when AJAX_REQUESTED is fired (others set to false)
  • success = true upon receiving AJAX_SUCCESS (others set to false)
  • error = true if AJAX_FAIL is dispatched (others set to false)

I aim to update state.open to false when isLoading transitions from true to false, and success changes to false to true.

I am seeking guidance on achieving this without complicating the state management.

Edit:

Below is my saga's code for handling events:

function* handleAjaxRequest(action) {
    try {
        yield call(api.doRequest);
        yield put({type: "AJAX_SUCCESS"});
    } catch (e) {
        yield put({type: "AJAX_FAILED"});
    }
}

export default function* () {
    yield [
        takeEvery("AJAX_REQUESTED", handleAjaxRequest),
    ]
}

Answer №1

If you want to respond to changes in Redux state within your component, you can make use of the componentWillReceiveProps() method. This function is triggered whenever there is an update to the redux property/state of your component, allowing you to adjust the local state accordingly.

In the context of your specific scenario:

componentWillReceiveProps(nextProps) {
  if (nextProps.loading !== this.props.loading &&
      nextProps.success !== this.props.success &&
      !nextProps.loading && nextprops.success) {
    this.setState({ open: false });
  }
}

This code snippet aligns perfectly with the behavior you have described. It may be beneficial to handle other conditions more dynamically for setting the state.open value, but addressing those scenarios goes beyond the scope of the original question.

For additional information and documentation, please refer to: https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops

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

How to effectively implement muistyled with a MUI component

import * as React from 'react'; import { styled } from '@mui/system'; const MyComponent = styled('div')({ color: 'darkslategray', backgroundColor: 'aliceblue', padding: 8, borderRadius: 4, }); exp ...

Ways to transfer Material-UI FlatButton CSS to a different Button element

I've recently incorporated a loading button object into my website from (https://github.com/mathieudutour/react-progress-button), and now I want to customize it using the Material-UI FlatButton CSS. However, I'm not quite sure how to achieve this ...

Encountering vulnerabilities during NPM installation, attempting to fix with 'npm audit fix' but unsuccessful

While working on my react project, I decided to incorporate react-icons by running npm install react-icons in the command prompt. However, after some time, the process resulted in the following errors: F:\Areebs\React JS\areeburrub>npm in ...

Enhancing nested structures in reducers

Currently, I am utilizing react, typescript, and redux to develop a basic application that helps me manage my ingredients. However, I am facing difficulties with my code implementation. Below is an excerpt of my code: In the file types.ts, I have declared ...

Module 'csstype' not found

I am diving into the world of React with TypeScript. After setting up react and react-dom, I also installed @types/react and @types/react-dom which all went smoothly. However, a pesky error message keeps popping up: ERROR in [at-loader] ./node_modules/@t ...

What causes the index to display [object Object] rather than an integer in React?

It has been a long time since I last worked with React, and now I'm facing an issue. Whenever I use console.log to display the index within the map function, my console output looks like this: https://i.stack.imgur.com/VbGmE.png However, the result ...

React and TypeScript warns about possible undefined object

certificate?: any; <S.Contents>{certificate[0]}</S.Contents> <S.Contents>{certificate[1]}</S.Contents> <S.Contents>{certificate[3]}</S.Contents> If I set the type of props to `any` and use it as an index of an array, e ...

An unexpected error occurred: ReferenceError - document is undefined

Error Alert: Unhandled Runtime Error ReferenceError: doc is not defined Source of Issue components\Modal.js (42:18) @ updateDoc 40 | await uploadString(imageRef, selectedFile, "data_url").then(async (snapshot) => { 41 | const do ...

When the height of the window decreases, scrolling is not implemented

Having trouble adjusting the height of my Responsive Modal when the window height decreases. The content is slipping under the window and the scroll bar isn't adjusting accordingly. It seems like the nested div structure is causing issues. https://i.s ...

A custom-designed Material UI TextField featuring a specific date and time picker capable of displaying seconds

Currently, I am facing an issue while using react-admin and trying to modify the date and time, specifically including seconds with the help of DateTimeInput. Unfortunately, my attempts have been unsuccessful so far. Here is what I have tried: Approach 1: ...

Encountered a java.io.IOException while trying to run react-native on Android, resulting in failure

ERROR: The build process was unsuccessful due to an exception. What caused the issue: The task ':app:transformClassesAndResourcesWithProguardForDebug' execution failed. java.io.IOException: Unable to write [/home/user/Desktop/pratap/react-pr ...

Error: Running the command 'yarn eg:'live-server'' is not a valid internal or external command

Currently, I am utilizing yarn v1.6.0 to manage dependencies. I have globally installed live-server by running the following command: yarn global-add live-server However, upon executing it as live server, I encounter the following error: 'live-ser ...

Select component experiencing issue with Material Ui label breaking

I've been working on implementing a select component, which is new to me. However, I'm encountering an issue with my MUI-select component. The label of the select element is no longer syncing properly with the select component itself as shown in ...

Create a customized design for the Tiptap editor to mimic the appearance of a Material UI

Is there a way to customize the appearance of a Tiptap editor to match that of a Material-UI text field, particularly the outlined or standard variant? I'm looking for a solution to make the border of the Tiptap editor resemble that of a Material-UI t ...

Creating a Triangle Slider Component with React and Material-UI (MUI)

Struggling with creating a price control using react js and MUI, similar to the image below: https://i.stack.imgur.com/ZP8oc.png I've searched online for libraries or solutions, but haven't found anything that works. ...

Concerns regarding code coverage when testing asynchronous functions using nockjs and jest

In my latest project, I've created a basic unit test for making API calls using NockJS and Jest within a React application. Here's a snippet of the code: AjaxService.js export const AjaxService = { post: (url, data, headers) => { ...

What is the best way to access form data in an AWS Lambda function coded in NodeJs?

In the process of constructing an application, I am utilizing ReactJS for the front-end and AWS API Gateway/AWS Lambda in NodeJS for the back-end. The form data from my React app is being passed within the userAttributes attribute as illustrated below: ht ...

Is there a way to programmatically prevent the back button from functioning if the previous route pathname in React was 'Login'?

When it comes to navigating back on previous pages, the traditional back button is typically used instead of relying solely on the navigation bar. However, I am currently looking to disable this feature specifically when the next previous route in line is ...

Potential Performance Issue with Material UI's withStyles Function

I've been given the task of optimizing the loading speed of a page in our react redux web app. When the page load action is triggered, there seems to be a slight freeze lasting about half a second. After checking the profiler, everything seems fine ...

Error: Attempting to access the 'getProvider' property of an undefined variable

I am encountering an error that says "property of undefined (reading getProvider)" while deploying my function to Firebase. I am currently trying to figure out how to obtain the auth instance. When I attempt to use firebase.auth, it results in another er ...