<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arash Kiani on Medium]]></title>
        <description><![CDATA[Stories by Arash Kiani on Medium]]></description>
        <link>https://medium.com/@arashkiani?source=rss-1859f64d683f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nZm_C_fYHdYvwzWY.jpg</url>
            <title>Stories by Arash Kiani on Medium</title>
            <link>https://medium.com/@arashkiani?source=rss-1859f64d683f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:10:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arashkiani/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[So you inherited a legacy React project now what? (redux)]]></title>
            <link>https://medium.com/@arashkiani/so-you-inherited-a-legacy-react-project-now-what-redux-d36bd84b496b?source=rss-1859f64d683f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d36bd84b496b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Arash Kiani]]></dc:creator>
            <pubDate>Fri, 31 Jan 2020 11:12:27 GMT</pubDate>
            <atom:updated>2020-01-31T11:22:59.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*meCFnZ5MK_7Fu1ogYfBvNQ.png" /></figure><p>This might be your first day at a new job or you’ve just got moved into a new team. all excited to work on a new set of problems; until you open the store / redux folder with many actions and reducers squeezed together. reducer with huge switch statements and actions that bleed through UI. fear not! here are the steps you can take in 2020 to reason with your Redux.</p><p><strong>Step one:</strong></p><p><em>Install `@reduxjs/toolkit`</em></p><p>ReduxToolkit is a small opinionated library that makes working with redux efficient. Once installed search for <strong>configureStore</strong> function which is probably going to have <strong>combineReducers</strong> passed into it.</p><p>&gt; Great now let’s write a test for it.</p><pre>import store from &quot;../&quot;;</pre><pre>test(‘should return identical object’, () =&gt; {</pre><pre>expect(store.dispatch({ type: ‘test’ })).toMatchInlineSnapshot();</pre><pre>expect(store.getState()).toMatchInlineSnapshot();</pre><pre>});</pre><p>ideally, this test should not break once we have replaced the engine underneath and can be deleted or adapted to test our store properly once we have refactored the code to use Redux-Toolkit.</p><p><strong>Step Two:</strong></p><p>Now that we have a test let’s replace our store from:</p><pre>import { createStore, applyMiddleware, compose, combineReducers } from ‘redux’;<br>import thunk from &#39;redux-thunk&#39;;<br>import myState from &#39;store/myState&#39;;<br>import { myMiddleware } from &#39;./middlewares&#39;;</pre><pre>const rootReducer = combineReducers({ myState });<br>const middlewares = [thunk, myMiddleware];<br>const composeEnhancers = process.env.NODE_ENV !== &#39;development&#39; ? compose : window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;</pre><pre>export default createStore(  reducers,  composeEnhancers(applyMiddleware(...middlewares)));</pre><p>into:</p><pre>import { configureStore, getDefaultMiddleware } from ‘@reduxjs/toolkit’;</pre><pre>import myState from &#39;store/myState&#39;;<br>import { myMiddleware } from ‘./middlewares’;</pre><pre>const rootReducer = { myState };<br>const middleware = [ …getDefaultMiddleware(), myMiddleware];</pre><pre>export default configureStore({ reducer: rootReducer, middleware, devTools: process.env.NODE_ENV === ‘development’ });</pre><p>No need to include `combineReducers`, `applyMiddleware`, `createStore` or even libraries such as `<strong>thunk` </strong>&amp;<strong> `logger`</strong>. they are all included. redux toolkit is even using the <strong>Immer </strong>library<strong> </strong>to make it easier to work with reducers.</p><p><strong>Step Three:</strong></p><p>Now that we have the basic setup the next step is to replace our reducer and actions with `createSlice` function that basically forces you to write true redux <a href="https://github.com/erikras/ducks-modular-redux">Ducks</a> by magically generating all your actions automagically from reducers.</p><pre>const initialState = {<br> isLoading: { user: false },<br> users: []<br>}</pre><pre>const slice = createSlice({<br>name: &#39;userState&#39;,<br>initialState,<br>reducers: {<br>  isLoading: (state, { payload: [type, action = false] }) =&gt; {<br>    state.isLoading[type] = action;<br>  },<br>  getUsersAction(state, { payload }) {<br>    state.users = payload;<br>  }<br>}<br>});</pre><pre>export actions = slice.actions<br>export default slice.reducer;</pre><p><em>No more switch statements, no more confusing spread operator.</em></p><p><strong>Step Four:</strong> (Thunk actions)</p><p>Now that we have a couple of actions and reducers, the next step is to pass data into them. this will probably get supplied through a promise via API. so let’s write a test to call a function that will dispatch a loading action, return users data and dispatch another action to disable loading once we dispatch the action.</p><pre>import { actions } from &#39;../userDuck&#39;;</pre><pre>test(&#39;Given that event is dispatched, List of users get dispatched&#39;, ()=&gt; {</pre><pre> // <a href="https://github.com/dmitry-zaets/redux-mock-store">Learn more about redux mock store</a><br> store.dispatch(actions.getUsersAction());</pre><pre> const data = [{ test: &#39;test&#39; }];</pre><pre> // <a href="https://www.npmjs.com/package/jest-mock-axios">Learn more on how to mock axios calls</a><br> mockAxios.mockResponseFor({ url: &#39;/users&#39;, method: &#39;get&#39; }, { data });</pre><pre> expect(mockAxios.get).toHaveBeenCalledTimes(1);<br> expect(mockAxios.get).toBeCalledWith(&#39;/users&#39;);</pre><pre> await flushPromises(); // to wait for dispatch promises fulfilment</pre><pre> const expectedResponse = [<br>  { payload: [&#39;users&#39;, true], type: &#39;usersState/isLoading&#39; },<br>  { payload: [&#39;users&#39;, false], type: &#39;usersState/isLoading&#39; }, <br>  { payload: data, type: &#39;usersState/getUsersAction&#39; }<br> ];</pre><pre> expect(store.getActions()).toEqual(expectedResponse);</pre><pre>});</pre><p>and now that we have our test lets write an action to fulfill pass our test</p><pre>const getUsersAction = () =&gt; async dispatch =&gt; {</pre><pre> dispatch(slice.actions.isLoading([&#39;users&#39;, true]));<br> const { error, data } = await api.getUsers();</pre><pre> dispatch(slice.actions.isLoading([&#39;users&#39;, false]));<br> dispatch(slice.actions.getUsersAction(data));</pre><pre>};</pre><pre>export const actions = { getUsersAction };</pre><h3>Conclusion</h3><p>Steps above are my way of cleaning the state and making redux boilerplate smaller and in turn redux more manageable to work within legacy projects.</p><h3>Other gotchas:</h3><p><strong>Modified eslint rules: </strong>reassign values to param is generally a bad idea but we are using immer.</p><pre>“rules”:{ <br> “no-param-reassign”: [“error”, { “props”: true, “ignorePropertyModificationsFor”: [“state”] }]<br>}</pre><p><strong>Testing multiple dispatches:</strong></p><p>Add this into your jest setup file to wait for dispatch promises.</p><pre>global.flushPromises = () =&gt; new Promise(setImmediate);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d36bd84b496b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>