React-Native/Redux dispatch firing multiple times in action

redux dispatch multiple actions at the same time
redux-saga dispatch multiple actions
mapdispatchtoprops multiple actions
redux dispatch action from reducer
vuex dispatch multiple actions
redux reducer called multiple times
redux chain actions
dispatch multiple actions react context

I'm making a React/Redux app. In one of my actions, dispatch is firing 6-8 times when called for no apparent reason. See addMarkersRequestAddress below in the action file for my component:

export function addMarkersSuccess(response) {
  return {
    type: 'addMarkersSuccess',
    status: 'success',
    response: response,
    receivedAt: Date.now(),
  };
}

export function addMarkersFailure(error) {
  return {
    type: 'addMarkersFailure',
    status: 'error',
    error: error,
    receivedAt: Date.now(),
  };
}

export function addMarkersRequestCoordinates(submitFormData) {


  // Why is this always returning addMarkersFailure? Is it possibly related to why it always fires multiple times?
  // Same code as in virtualFenceWalk actions
  return (dispatch) => {

    console.log('running addMarkersRequestCoordinates');
    console.log('submitFormData: ',submitFormData);

    let JSONbody = JSON.stringify(submitFormData);
    console.log('JSONbody: ',JSONbody);

    fetch('http://localhost:8080/virtualFence', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSONbody
        }).then(function(response){
          dispatch(addMarkersSuccess(response));
        }).catch(function(error) {
          dispatch(addMarkersFailure(error));
        });

  }
}

export function addMarkersRequestAddress(submitFormData) {
  return (dispatch) => {

    console.log('running addMarkersRequestAddress');
    console.log('submitFormData: ',submitFormData);

    let JSONbody = JSON.stringify(submitFormData);
    console.log('JSONbody: ',JSONbody);

    // Make a request to a backend route that gets the coordinates from the Google Maps API
    fetch('http://localhost:8080/virtualFenceAddress', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSONbody
        }).then(function(response){
          console.log('addMarkersRequestAddress success');
          console.log('response: ',response);
          dispatch(addMarkersSuccess(response));
        }).catch(function(error) {
          console.log('addMarkersRequestAddress failure');
          console.log('error: ',error);
          dispatch(addMarkersFailure(error));
        });

  }

}

When this code runs, addMarkersSuccess will fire 6-8 times. It is somehow related to dispatch specifically, because if I remove the dispatch calls and leave only the console logs, addMarkersSuccess fires once as expected and that's it. It also seems unrelated to fetch or asynchronicity since an identical outcome occurs if fetch is removed and the same thing is tried in the main body of the function.

Here is the container wrapping around the component (since I've narrowed it down to an issue with how dispatch is called, as without dispatch other parts of the action only fire once, maybe there is an issue with how dispatch is set up here?):

import React, { Component }                                             from 'react';
import PropTypes                                                        from 'prop-types';
import { StyleSheet, View, Text, TouchableOpacity, TouchableHighlight } from 'react-native';
import { bindActionCreators }                                           from 'redux';
import { connect }                                                      from 'react-redux';
import VirtualFence                                                     from '../components/VirtualFence';
import * as VirtualFenceActions                                         from '../actions/virtualFence';

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  back: {
    margin: 10,
    fontSize: 20,
  },
});

// Map the Redux state to props
@connect(
  state => ({
    bigState: state,
    markers: state.markers,
  }),
  dispatch => bindActionCreators(VirtualFenceActions, dispatch),
)

export default class VirtualFenceContainer extends Component {

  render() {
    return (
      <View style={styles.container}>
        <VirtualFence {...this.props} />
      </View>
    );
  }
}

Here is where the action is called in the component itself:

render() {

    const {
      addMarkersRequestAddress, addMarkersSuccess, addMarkersFailure
    } = this.props;

    return (
      <View>
        <TouchableOpacity onPress={this.toggleModal}>
          <Text style={styles.bottomText}>Add markers by street address</Text>
        </TouchableOpacity>
        <Modal isVisible={this.state.isVisible}>
          <View style={{ flex: 1 }}>
            <TouchableOpacity onPress={this.toggleModal}>
              <Text style={styles.bottomText}>Hide me!</Text>
            </TouchableOpacity>
            <Form
              ref="form"
              type={Points}
              options={pointsOptions}
            />
            <Button title="Add form field" onPress={this.addFormField}></Button>
            <Button title="Delete form field" onPress={this.deleteFormField}></Button>
            <Button
              title="Submit markers"
              onPress={(argument)=>addMarkersRequestAddress(this.refs.form.getValue())}
            />
          </View>
        </Modal>
      </View>
    );
  }

While not answering my question, some other answers here and elsewhere seemed to hint that the resolution may have something to do with my configureStore.js file, so here it is:

/* eslint global-require: 0 */

import { Platform } from 'react-native';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducers';

// Presumably I need to add the other action files here somehow? Nothing seems to change as long as one file is listed...
import * as actionCreators from './actions/activityTracker';

let composeEnhancers = compose;
if (__DEV__) {
  // Use it if Remote debugging with RNDebugger, otherwise use remote-redux-devtools
  /* eslint-disable no-underscore-dangle */
  composeEnhancers = (window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ||
    require('remote-redux-devtools').composeWithDevTools)({
    name: Platform.OS,
    ...require('../package.json').remotedev,
    actionCreators,
  });
  /* eslint-enable no-underscore-dangle */
}

const enhancer = composeEnhancers(applyMiddleware(thunk));

// I think the problem with multiple dispatches may be in here
// See https://stackoverflow.com/questions/49734848/redux-dispatch-fires-multiple-times
export default function configureStore(initialState) {
  const store = createStore(reducer, initialState, enhancer);
  if (module.hot) {
    module.hot.accept(() => {
      store.replaceReducer(require('./reducers').default);
    });
  }
  return store;
}

Please note that I don't really know what this file is doing. I began the app using react-native-boilerplate so this file is taken from there. If changes need to be made there, it would be super appreciated if you can detail what exactly those changes do.

EDIT 1: When this post was originally written, all dispatches after the first threw errors. After some further work in other parts of the application, the additional firings all log successful now. However, the essential question (the cause of the multiple firings) remains.

EDIT 2: Added the container wrapping around the component.

The cause of my problem turned out to be in the file where I call the combineReducers helper function. I did not suspect this file had anything to do with the problem, so I had not posted it. For components with multiple keys in the initial state object, I incorrectly thought I had to do an import for each key, when in fact I needed a single import for each reducer file. I imported six variables from the virtualFence reducer, and each one caused dispatch to fire.

This is the incorrect version:

import { combineReducers }       from 'redux';
import nav                       from './nav';
import virtualFence              from './virtualFence';
import latitude                  from './virtualFence';
import longitude                 from './virtualFence';
import latitudeDelta             from './virtualFence';
import longitudeDelta            from './virtualFence';
import markers                   from './virtualFence';

export default combineReducers({
  nav,
  latitude,
  longitude,
  latitudeDelta,
  longitudeDelta,
  markers,
  virtualFence,
});

And this is the correct version:

import { combineReducers }           from 'redux';
import nav                           from './nav';
import virtualFence                  from './virtualFence';

export default combineReducers({
  nav,
  virtualFence,
});

redux dispatch fires multiple times, You're registering an extra event handler to the socket on each getData call. Instead, you should register just one handler on initialization and  Actions only need to be serializable by the time they actually reach the store and are passed to the reducers. We can't reliably enforce serializable actions for performance reasons, so Redux only checks that every action is a plain object, and that the type is defined.

are you using preventDefault() when calling event this might be the case:

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

use preventdefault to disallow to call method when page is loading

<Button title="Add form field" onPress={this.addFormField}></Button>
            <Button title="Delete form field" onPress={this.deleteFormField}></Button>
            <Button
              title="Submit markers"
              onPress={(argument)=>addMarkersRequestAddress(this.refs.form.getValue())}
            />

React Redux: performance considerations when dispatching , In a React Redux app, what happens when you dispatch multiple actions in a row​? React will re-render multiple times; React Redux will re-evaluate selectors renderer packages like ReactDOM and React Native, not the React core itself. posted in Flux, Javascript, Redux on October 21, 2015. When using Redux, you may have come across a scenario where you’d like one action creator to dispatch multiple actions. There are a few reasons you’d want to do this, but let’s consider the problem of handling a submit event from a form.

So you state:

addMarkersSuccess will fire once, followed by several firings of addMarkersFailure

addMarkersFailure only gets called when there is an error. This error, of course, contains all the information you need to solve the problem. In particular, it has a stack that indicates not only the exact place the error was fired, but a complete call stack that indicates the entire call chain leading up to the error.

When a Promise has several stages, each stage has an opportunity to fail. A catch following any of the stages will be passed the error.

So:

Promise.resolve('This is just a string, and no error')
  .then(theString => {
    throw new Error('This is not the original promise result, but a new one: A rejection.');
  })
  .catch(err => {
    console.log('Something went wrong. Maybe it happened in the original promise.');
    console.log('Maybe it happened later. To find out, look closely at this:');
    console.log(err.stack);
  });

In your case, it's probably dispatch that throws. Now, there's nothing wrong with dispatch itself, but when it goes to call your reducer, the reducer is probably doing something wrong and throwing an error. This in turn leads your .catch callback (aka the rejection handler) to be called.

Since you did not include your reducer code I can't point out the error in it. However, you should be able to find it by examining the error message and stack.

Can I dispatch multiple actions from Redux action creators?, So should you dispatch separate actions for each of these behaviours, redux-​thunk middleware, aren't we definitely calling dispatch multiple times? reduxMulti, )(createStore) // Ensure our listeners are only called once, even PDF cheatsheets – for React (see preview), ES6 and JavaScript promises! Shouldn't this be a single dispatch call firing a single network request? What I see is that I have multiple API calls for same endpoint flooding my network tab. I don't have any setInterval in my action creators or epics. But still they go on. Any way to mitigate this. I'm linking an issue which is related to this.

In your addMarkersRequestAddress action, try to return the dispatch in .then() like:

.then((response) => {
      dispatch(addMarkersSuccess(response));
    }).catch((error) => {
      dispatch(addMarkersFailure(error));
    });

Maybe this will work.

Multiple Actions one dispatch? · Issue #959 · reduxjs/redux · GitHub, Is there currently a way to dispatch multiple actions atomically (is that the right I suppose I mean two or more actions sent in succession which only other means, rather than a raw JS value as shown in the example. a post on How to React a editing form #13 You can't perform that action at this time. You call store.dispatch to dispatch an action. This is the only way to trigger a state change. This is the only way to trigger a state change. With React Redux, your components never access the store directly - connect does it for you.

dispatch(action) calls reducer twice but this.props.function not · Issue , The strang thing is: When I call the action through the function I am passing in through mapDis When I am using the this.props.dispatch(action) the reducer gets called twice. import * as React from 'react'; import { connect } from 'react-​redux'; import { toggleNavigation } from '. You can't perform that action at this time. The dispatch() function can be accessed directly from the store as store.dispatch(), but more likely you'll access it using a helper like react-redux's connect(). You can use bindActionCreators() to automatically bind many action creators to a dispatch() function. Action creators can also be asynchronous and have side-effects.

4 ways to dispatch actions with Redux - Blogs, Redux is a state container for Javascript apps, mostly used with React. We're creating a form, MessageSending.js, and when pressing the SEND button, we If you want to dispatch several actions in one method you can do like that: you start to have logic in your mapDispatchToProps function, it's time to dispatch action  React Redux re-evaluates selectors multiple times. The batch function only solves half of the problem:. each dispatched action would still result in a separate notification of subscribers (and

Fullstack React: Redux actions, But there currently isn't any way to update to the new time. Rather than dispatch the action directly, we'll use a function to return an action the Let's create our first actionCreator in a file called redux/actionCreators.js . Redux has a way for us to split up our redux reducers into multiple reducers, each responsible for  Usually, for any API request you'll want to dispatch at least three different kinds of actions: An action informing the reducers that the request began. The reducers may handle this action by toggling an isFetching flag in the state. This way the UI knows it's time to show a spinner.

Comments
  • Can you show how you use these actions in your component? Please show a minimal reproducible example. Note the word "complete".
  • I've added the render function from the component where this action is called.
  • Please read the link I gave in my previous comment.
  • Where are you executing the addMarkersRequestCoordinates function? Your reducer action seems ok.
  • I did read the link. What is the issue?
  • This doesn't fix it. I created a wrapper function called onPress with e.preventDefault() that then called addMarkersRequestAddress, but multiple dispatches remained.
  • I didn't include reducer code because the error occurs even if the entire content of the reducer is simply return state. As such, I feel I've reliably identified that the reducer itself is not the problem. Regardless, this doesn't really address why the dispatch call actually works the first time.
  • Have you inspected the error? What is the error message?
  • Just tried it again this morning--and instead of getting an error, I get a successful dispatch 6 times. I've done some further work on the code since originally posting this. This additional work mostly relates to incorporating Immutable.js throughout the entire flow of the application, so that may have somehow solved what caused the failures. But the multiple dispatch problem remains, and that is what needs to get solved.
  • I do return the dispatch in then() already. Is your point to use fat arrow functions?
  • My point is somehow return the dispatch because it seems the function are not returning.
  • Your code does not differ from mine in any way except for the use of a fat arrow function.
  • I think you should return the response to your function: try this return fetch('http://localhost:8080/virtualFenceAddress', ...
  • The same behavior remains when using return.