How to fire a Redux Action without a React

Asked

Viewed 407 times

2

Hi, I’m creating a Interceptor to the Xios which, if my Answer case there is an error with the status Forbidden (403) the same need to trigger the Action that starts the user’s logoff to force him to re-use.

This is necessary because it triggers a series of cascading actions and is already configured for such a feature.

My problem is that I don’t know how to connect a function to Redux without having a React component. So far my Interceptor is this way:

import axios from 'axios'
import { logoffRequest } from 'store/actions/userActions'

axios.interceptors.response.use(
  response => response,
  error => {
    if (403 === error.response.status) {
      logoffRequest()
    }
  }
)

The action logoffRequest depends on a Redux to work because it moves a lot of states of the application, including sending data to the backend...

What I need to do to make it possible to call this Action from within this Interceptor?

2 answers

1

You can get an instance of your store and use the dispatch.

import axios from 'axios'
import { logoffRequest } from 'store/actions/userActions'
import { store } from '/caminho'


axios.interceptors.response.use(
  response => response,
  error => {
    if (403 === error.response.status) {
      store.dispatch(logoffRequest())
    }
  }
)
  • But if I do this, when I pull the store from a file I will ta calling again the creation of it and I will lose the information no?

  • 1

    @Leandroluk I believe not, tested this code?

  • did not get to testing, I resolved encapsulating the declaration of interceptors within a function that receives the store itself.

0

I was able to solve my problem by placing the interceptors declaration in a function that receives the store, so I can call this creation of the interceptors right after the store index.js thus:

src/lib/Axios.interceptors.js

import axios from 'axios'
import { logoffRequest } from 'store/actions/userActions'

export default store => {
  axios.interceptors.response.use(
    response => response,
    error => {
      if (403 === error.response.status) {
        store.dispatch(logoffRequest())
      }
    }
  )
}

src/index.js

// ... outros imports (pra reduzir o exemplo...)

import axiosInterceptors from './lib/axios-interceptors'

const store = configureStore(history, initialState)
const rootElement = document.getElementById('*')

axiosInterceptors(store)

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Views />
    </ConnectedRouter>
  </Provider>,
  rootElement
)

This way I have the guarantee that the application will start containing the Interceptor and that it is using the only and correct store that is being passed to the general project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.