N3TC4T
N3TC4T

Reputation: 198

Calling action from ouside of redux

I need to call an redux action from ouside of my redux app , like in an external js file . I have an api.js file that handle REST requests and All i need is calling an action in success response and handeling action by my middleware .

the proplem is i can't access store or dispatch in api.js file even if i export my store beacuse it's not connected to redux or any react component .

api.js

function ApiRequest(url) {
    return fetch(thisUrl)
        .then(async (rawRes) => {
            if (rawRes && rawRes.status === 200) { 
                // <------- Here i wanna run redux action 
            }

        })
        .catch((err) => {
            console.log(err)
        });

}

apiMiddleware :

const apiMiddleware = store => next => (action) => {
  switch (action.type) {
    case 'API_SUCCESS_RESPONSE' :
      console.log('action success executed')
      break;

    default :
  }
  return next(action);
};

export default apiMiddleware;

any suggestion ?

Upvotes: 0

Views: 508

Answers (1)

intentionally-left-nil
intentionally-left-nil

Reputation: 8274

Basically, if you have access to the store, you can dispatch actions at any point.

So the solution to your issue comes down to "how do I provide access to the store variable inside of ApiRequest? There are many solutions to the problem. A global variable assigning store to Window is the easiest.

However, global solutions end up with issues of implicit ordering (the store has to be initialized before an ApiRequest) among other issues.

For example, assuming that you assign window.store = store when creating your redux store, then your code would look like this:

function ApiRequest(url) {
    return fetch(thisUrl)
        .then(async (rawRes) => {
            if (rawRes && rawRes.status === 200) { 
                store.dispatch({type: 'API_SUCCESS_RESPONSE' })`
            }

        })
        .catch((err) => {
            console.log(err)
        });

}

Edit: To be clear, from your question apiMiddleware is not the store. ApiMiddleware is a function that given an already created store, wraps it in middleware. There is code somewhere in your program which looks like this:

import { createStore } from 'redux'
export apiMiddleware from './apiMiddleware'
const store = createStore(reducers, apiMiddleware)

then ^^^ this is the store you want to export globally.

Upvotes: 2

Related Questions