I have a global toast, which I am opening using redux slice. I need to open the toast for error message when call from api fails in api-slice of rtk-query.
I have seen the answer, using store.dispatch
method, but this causes dependency cycle. Is there a way to do this?
Asked
Active
Viewed 1,246 times
1

Beginner
- 182
- 2
- 14
-
adding some code snippet could help knowing the structure of your redux slice – Bms bharadwaj Jan 11 '22 at 16:58
1 Answers
2
Yeah, you should always avoid directly importing the store into other application files.
Ideally, none of the rest of your code would ever need to refer to store
directly.
Depending on where in the RTKQ setup you need to trigger this toast, you may have access to dispatch
as part of the lifecycle function arguments.
In the worst case, you can use our fallback recommendation to inject the store into the necessary files from the app setup logic.

markerikson
- 63,178
- 10
- 141
- 157
-
While this does solve the problem, but in this way, I will have to do this for every endpoint which is repetitive. How I handled it was to create a custom middleware and listen for query fulfilled action. Then according to the payload received dispatch the toast action. This solution solves my problem but might not work for every use case. – Beginner Jan 11 '22 at 18:35
-
1Yep, that does sound like a good use for a custom middleware! You may also want to try using [our upcoming "action listener" middleware](https://github.com/reduxjs/redux-toolkit/discussions/1648), which is meant to make it simple to write code that runs in response to specific actions. Should make this particular use case pretty simple to handle. It's in alpha atm, but the API has mostly stabilized, and we'd like folks to try it and give us feedback. – markerikson Jan 11 '22 at 18:40