What is the correct way to combine redux-thunk and redux-batched-actions? - redux

What is the correct way to plug redux-batched-actions into my existing Redux store? I am completely confused by the Redux middleware API.
Currently I am using redux-thunk and redux-little-router.
Here is the code source that creates my Redux store:
import { createStore, applyMiddleware, compose, combineReducers } from 'redux'
import thunk from 'redux-thunk'
import { routerForBrowser } from 'redux-little-router'
import reducers from './store'
import routes from './routes'
const { reducer, middleware, enhancer } = routerForBrowser({ routes })
// Combine all reducers and instantiate the app-wide store instance
const allReducers = combineReducers({ ...reducers, router: reducer })
// Build middleware (if devTools is installed, connect to it)
const allEnhancers = (window.__REDUX_DEVTOOLS_EXTENSION__
? compose(
enhancer,
applyMiddleware(thunk, middleware),
window.__REDUX_DEVTOOLS_EXTENSION__())
: compose(
enhancer,
applyMiddleware(thunk, middleware)))
// Instantiate the app-wide store instance
const initialState = window.initialReduxState
const store = createStore(
allReducers,
initialState,
allEnhancers
)
The redux-batched-actions documentation exposes two usages: enableBatching and batchDispatchMiddleware. Which one should I use in my case?

Answering my own question after the return of my expedition into the fabulous source code of redux, redux-thunk, redux-batched-actions, ...
The correct way to do it seems to be using batchDispatchMiddleware, like this:
import { batchDispatchMiddleware } from 'redux-batched-actions'
// ...
const allEnhancers = (window.__REDUX_DEVTOOLS_EXTENSION__
? compose(
enhancer,
applyMiddleware(batchDispatchMiddleware, thunk, middleware),
window.__REDUX_DEVTOOLS_EXTENSION__())
: compose(
enhancer,
applyMiddleware(batchDispatchMiddleware, thunk, middleware)))
Note: I don't know if I could dispatch batched thunks, though. I don't do that in my current application. Use at your own risk!

Related

ReduxSaga makes my website re-render infinite

Im using Redux-Saga and Redux-Thunk, this is store I have configured, but it makes my website re-render infinitely. Can u tell me what should i do to solve that? Thank u.
Store.js
import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from '#redux-saga/core'
import EmployeeReducer from './reducers/EmployeeReducer'
import thunk from 'redux-thunk'
import axiosMiddleware from "redux-axios-middleware";
import HttpService from "app/services/HttpService";
import RootReducer from './reducers/RootReducer'
import {getEmployeeList} from './saga'
const initialState = {};
const sagaMiddleware = createSagaMiddleware()
const middlewares = [
thunk,
sagaMiddleware,
axiosMiddleware(HttpService.getAxiosClient())
];
export const Store = createStore(
RootReducer,
initialState,
compose(
applyMiddleware(...middlewares)
)
);
sagaMiddleware.run(getEmployeeList)
This is saga.js where i import getEmployeeList
import { call, cancel, put, takeEvery, takeLatest } from 'redux-saga/effects'
import axios from 'axios'
import { GET_EMPLOYEE_LIST } from './actions/EmployeeActions'
import ConstantList from '../../app/appConfig'
const API_PATH = ConstantList.API_ENPOINT + "/employees"
export function* getEmployeeList() {
yield takeEvery(GET_EMPLOYEE_LIST, workEmployeeList)
}
export function* workEmployeeList() {
console.trace("hello");
try {
const url = API_PATH + '/search'
const response = yield call(axios.post, url, {})
yield put({
type: GET_EMPLOYEE_LIST,
payload: response.data.data
})
} catch (error) {
console.log("Request failed!")
}
}
The issue is that you are using the same action type to start the saga & to store the results to redux store.
// here you are waiting for GET_EMPLOYEE_LIST to trigger the saga
yield takeEvery(GET_EMPLOYEE_LIST, workEmployeeList)
// here you are using the same action type to store
// response data to redux store
yield put({
type: GET_EMPLOYEE_LIST,
payload: response.data.data
})
Because of that every time you finish fetching data another saga is triggered.
What you want is to have another action type to store the data in redux store like FETCH_EMPLOYEE_LIST_SUCCESS. Don't forget to update your reducer condition to use the correct action type as well.
You built yourself an infinite loop here:
yield takeEvery(GET_EMPLOYEE_LIST, workEmployeeList)
this means: "every time, GET_EMPLOYEE_LIST is dispatched, execute workEmployeeList"
And in workEmployeeList you have:
yield put({
type: GET_EMPLOYEE_LIST,
payload: response.data.data
})
this means "dispatch GET_EMPLOYEE_LIST".
So 1. leads to 2. and 2. leads to 1.
I can't really suggest anything to fix this as this is missing a lot of building blocks to work in the first place.
But what I can tell you is that we as Redux maintainers really recommend against using sagas for tasks like data fetching.
If you want to know about the backgrounds, I would recommend you watch the evolution of Redux Async Logic.
But generally, seeing you are just getting into Redux, my advice would be to really take a step back and go through our official Redux Tutorial first.
Not only shows it modern (post-2019) Redux which is about 1/4 of the code you are writing here and a lot less confusing, but it also shows multiple different approaches to data fetching.

Is it okay to use Redux Toolkit and Redux Saga together?

is it ok to use the Redux Toolkit, even if I only create Slice in it and solve middleware via Redux Saga?
Or the best practice, in this case, is to use Redux Saga + raw Redux without Toolkit?
Thanks
Redux-saga is just a middleware that handles async logic better. If you have a large-scale app, redux-saga is preferred over redux-thunk. redux-saga makes the testing easier.
the difference between Redux and Redux toolkit is redux toolkit requires less code to set up and redux-toolkit uses immer.js to update the state easier.
To integrate redux-saga with redux-toolkit, you write your sagas and then combine them
import { all } from "redux-saga/effects";
import { firstSaga } from "./firstSaga";
export default function* rootSaga() {
yield all([...firstSaga]);
}
and then in store.js
import { configureStore } from "#reduxjs/toolkit";
import createSagaMiddleware from "redux-saga";
import rootSaga from "./rootSaga";
const sagaMiddleware = createSagaMiddleware();
const store = configureStore({
reducer: {
movie: MovieReducer,
},
middleware: (getDefaultMiddleware) =>
// adding the saga middleware here
getDefaultMiddleware().concat(sagaMiddleware),
});
sagaMiddleware.run(rootSaga);
export default store;

React / Redux - Error: Actions must be plain objects. Use custom middleware for async actions

I am getting this error even though I am using redux thunk. Redux store is also set up correctly (I think). I am creating a MERN app and I want to send a POST request to the backend (form submit) to create a new user. The request and response from the server are fine (checked using Postman). I just can not find where the problem is. The action creator which is causing this is :-
import axios from "axios";
export function signupUser(newuser) {
return function (dispatch) {
axios.post("/auth", newuser).then((res) => {
// dispatch
dispatch({
type: "ADDNEW_USER",
payload: res.data,
});
});
};
}
The store setup is :-
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers";
const initialState = {};
// const middleware = [thunk];
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
export default store;
The Signup.js component is ->
[Signup.js][1]
and the error is -> [here][2]
[1]: https://paste.ubuntu.com/p/gCX3wQPt9X/
[2]: https://imgur.com/a/6SDmydw

Integrating redux with aws-appsync

Is there any way to integrate redux with aws-appsync in react-native?
If there is can you give me hint or clue on how to do it? I'm having a hard time integrating it. Thank you in advance.
I think you should be able to connect your own redux store as is detailed in their documentation. Basically create your own and use connect(mapStateToProps, mapDispatchToProps) from react-redux to connect your components.
const MyComponent = props => <h1>HI!</h1>
const ReduxConnected = connect(mapStateToProps, mapDispatchToProps)(MyComponent)
const GraphQLConnected = graphql(gql`query { hi }`)(ReduxConnected)
And then at the root of your application have
import AWSAppSyncClient from "aws-appsync";
import { Provider as ReduxProvider } from 'react-redux'
import { graphql, ApolloProvider } from 'react-apollo';
import { Rehydrated } from 'aws-appsync-react';
import { createStore } from 'redux'
const client = new AWSAppSyncClient({...})
const store = createStore({...})
const ConnectedApp = () =>
<ApolloProvider client={client}>
<Rehydrated>
<ReduxProvider store={store}>
<App />
</ReduxProvider>
</Rehydrated>
</ApolloProvider>
I haven't had a chance to try this setup but I will soon and will edit with any findings. In the meantime here is a link showing how to build a full RN app with AppSync that uses MobX instead of Redux (https://github.com/dabit3/heard) that may also be a good place to start.

update redux reducers after store initialization

I am new to redux architecture, I have this basic doubt can we update the reducers list after creating the store using combinedReducer and createStore methods?
Yes, you can update the reducers and inject a new one asynchronously with replaceReducer api of Redux store.
It is an advanced API. You might need this if your app implements code
splitting, and you want to load some of the reducers dynamically. You
might also need this if you implement a hot reloading mechanism for
Redux.
Take as example this starter-kit
In createStore.js file the reducers passed as arguments to the createStore method are the result of makeRootReducers(). Pay attention to the fact that no one async reducer have been passed to this function.
// extract of src/store/createStore.js
import { applyMiddleware, compose, createStore } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import thunk from 'redux-thunk'
import makeRootReducer from './reducers'
export default (initialState = {}, history) => {
// ...
// ======================================================
// Store Instantiation and HMR Setup
// ======================================================
const store = createStore(
makeRootReducer(), // <------------- without arguments, it returns only the synchronously reducers
initialState,
compose(
applyMiddleware(...middleware),
...enhancers
)
)
store.asyncReducers = {}
// ...
}
In reducers.js file:
makeRootReducer function calls combineReducers with the default reducers
needed for the startup (like router reducer) and other "asynchronously" reducers passed as arguments
injectReducer is a function called for injecting new reducers on runtime. It call replaceReducer api on the store passing as argument a new list of reducers obtain through makeRootReducer(async) function
see below:
// src/store/reducers.js
import { combineReducers } from 'redux'
import { routerReducer as router } from 'react-router-redux'
export const makeRootReducer = (asyncReducers) => {
return combineReducers({
// Add sync reducers here
router,
...asyncReducers
})
}
export const injectReducer = (store, { key, reducer }) => {
store.asyncReducers[key] = reducer
store.replaceReducer(makeRootReducer(store.asyncReducers))
}
export default makeRootReducer
Finally, in the starter-kit the reducer is injected on route definition, like here:
// src/routes/Counter/index.js
import { injectReducer } from '../../store/reducers'
export default (store) => ({
path: 'counter',
/* Async getComponent is only invoked when route matches */
getComponent (nextState, cb) {
/* Webpack - use 'require.ensure' to create a split point
and embed an async module loader (jsonp) when bundling */
require.ensure([], (require) => {
/* Webpack - use require callback to define
dependencies for bundling */
const Counter = require('./containers/CounterContainer').default
const reducer = require('./modules/counter').default
/* ----> HERE <---- */
/* Add the reducer to the store on key 'counter' */
injectReducer(store, { key: 'counter', reducer }) // <-------
/* Return getComponent */
cb(null, Counter)
/* Webpack named bundle */
}, 'counter')
}
This technique is helpful when you want split a large app and avoid to load all the reducers at the boot.

Resources