Search code examples
reactjsreduxreact-reduxredux-thunk

Triggering notification to 3rd party endpoint from inside reducer: yay or nay?


I am using React-Redux with redux thunks for a web app that interacts with a remote SDK and syncs state with that SDK.

Beyond this remote SDK, I also have a third party endpoint that I want to send lifecycle updates to. When a specific page loads, or a checkpoint in my react application is reached, I want to notify the endpoint that these events occurred. I do not care about this endpoint's response, and I do not execute any store updates based on this response. The third party endpoint executes some of its own logic when it's notified of this event. You could consider it a "logging" function.

Specifically, I am interested in triggering this POST request when the Redux store is updated to a certain state.

I have this method to post the request to the endpoint:

export const lifecycleEndpointNotify = (event: string) => {
    console.log(event)
      const call = lifecycleEndpoint(event)
      console.log(call)
      return fetch(call, {
          method :'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            code: 200,
            message: 'Lifecycle event occured.',
          })
      })
      .then(
        response => console.log(response),
        error => console.log('An error occured.', error)
      )
  }

What is the appropriate place to put this function call? Since I want to trigger this event once a specific react action is called and the store is updated, the reducer makes the most sense to me as the place to put it. However, since it's technically triggering a side effect, I am not sure if putting it in the reducer violates redux norms. Other options would be for me to call this event inside my thunk action function right before I trigger a dispatch() call to update the store. This would, however, not link the event directly to the action itself. How can I call this event whenever a specific action is dispatched, or a specific change in the store occurs, like when some variable switches from true to false?


Solution

  • You never call asynchronous functions inside reducer. You want this to be called inside action. Reducer is only for updating store.

    In the react component make handler which is checking the store(e.g. in componentDidUpdate method) and when you get the certain store just hit to the dispatch function which will receive action argument with value you want to pass with the POST request. Then you need to create action which will make asynchronous call. You can do this using redux-thunk. If you are not familiar with this approach please let me know. I'll try to make sample for you in https://codesandbox.io/.