{"id":8338,"date":"2021-02-10T17:28:41","date_gmt":"2021-02-10T11:58:41","guid":{"rendered":"https:\/\/www.h2kinfosys.com\/blog\/?p=8338"},"modified":"2021-02-10T17:28:42","modified_gmt":"2021-02-10T11:58:42","slug":"session-management-using-redux","status":"publish","type":"post","link":"https:\/\/www.h2kinfosys.com\/blog\/session-management-using-redux\/","title":{"rendered":"Session Management Using Redux"},"content":{"rendered":"\n<p>Redux is a predictable state container for creating <a href=\"https:\/\/simple.wikipedia.org\/wiki\/JavaScript\" class=\"rank-math-link\" rel=\"nofollow noopener\" target=\"_blank\">JavaScript applications<\/a>. It helps you in writing applications that behave consistently, run in different environments (client, server, and native), and are easy to test. You can say that Redux is a state management tool.<\/p>\n\n\n\n<p>The way Redux works is simple. A central store holds the entire state of the application and each component can access the stored state without having to send the down props from one component to another.<\/p>\n\n\n\n<p>There are three building parts in Redux: actions, store, and reducers.<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Actions in Redux: Actions are events and the only way you can send data from your application to the Redux store. The data can either be from user interactions, API calls, or even form submissions.<\/li><\/ol>\n\n\n\n<p>Actions are sent using the method store.dispatch(). Actions are the plain JavaScript objects, and they must contain a type property to indicate the type of action to be carried out. They must have a payload that contains the information that should be worked on by the action. Actions are created via an action creator.<\/p>\n\n\n\n<ol class=\"wp-block-list\" start=\"2\"><li>Reducers in Redux: Reducers are the pure functions that take current state of an application, perform an action, and return a new state. These states are always stored as objects, and specify how the state of an application changes in response to the action sent to the store.<\/li><\/ol>\n\n\n\n<p>It is also based on the reduce <a href=\"https:\/\/www.h2kinfosys.com\/blog\/what-is-javascript\/\" class=\"rank-math-link\">function in JavaScript<\/a>, where a single value is calculated from the multiple values after a callback function has been carried out.<\/p>\n\n\n\n<ol class=\"wp-block-list\" start=\"3\"><li>Store in Redux: The store holds the application state. There is only one store available in any Redux application. You can access the state stored, update the state, and register or unregister listeners via helper methods.<\/li><\/ol>\n\n\n\n<p>Other benefits of using Redux are:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Redux make the state predictable: In Redux, the state always remain predictable. If the same state and actions are passed to a reducer, the same result is always produced since reducers are pure functions. The state is also immutable and never change. This makes it possible to implement the arduous tasks such as infinite undo and redo. It is possible to implement time travel, i.e, the ability to move back and forth between the previous states and view the results in real-time.<\/li><li>Maintainability: Redux is strict about how the code should be organized that makes it easier for someone having knowledge of Redux to understand the structure of any application of Redux. This makes it easier to maintain.<\/li><li>Debuggable for days: Redux also makes it easy to debug an application. By logging the actions and state, it is easy to understand coding errors, network errors, and other forms of bugs that may come up during production.<\/li><li>Ease of testing: It is also easy to test Redux apps since functions are used to change pure functions.<\/li><li>State persistence: You can also persist some of the app&#8217;s state to local storage and restore it after a refresh.<\/li><li>Server-side rendering: Redux can be used for <a href=\"https:\/\/redux.js.org\/recipes\/server-rendering\" class=\"rank-math-link\" rel=\"nofollow noopener\" target=\"_blank\">server-side rendering<\/a>. With it, you can handle the app&#8217;s initial render by sending the state of an app to the server along with the response to the server request. The required components are rendered in HTML and sent to the clients.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to Create a React App using Redux?<\/strong><\/h2>\n\n\n\n<p><strong>Step 1: <\/strong>src\/redux\/users.js<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import { createSlice } from 'redux-starter-kit';\nimport faker from 'faker';\nconst users = [...new Array(1000)].map(() => ({\n\u00a0\u00a0id: faker.random.uuid(),\n\u00a0\u00a0avatar: faker.image.avatar(),\n\u00a0\u00a0username: faker.internet.userName(),\n\u00a0\u00a0name: `${faker.name.firstName()} ${faker.name.lastName()}`,\n}));\nconst { actions, reducer } = createSlice({\n\u00a0\u00a0initialState: {\n\u00a0\u00a0\u00a0\u00a0users,\n\u00a0\u00a0\u00a0\u00a0selected: null,\n\u00a0\u00a0},\n\u00a0\u00a0reducers: {\n\u00a0\u00a0\u00a0\u00a0selectUser(state, { payload: user }) {\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0state.selected = user || null;\n\u00a0\u00a0\u00a0\u00a0},\n\u00a0\u00a0},\n});\nexport const { selectUser } = actions;\nexport default reducer;\n<\/pre>\n\n\n\n<p><strong>Step 2: <\/strong>You\u2019ll also need to create a store to manage the state for each piece.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">src\/redux\/index.js\nimport { configureStore } from 'redux-starter-kit';\nimport users from '.\/users';\nexport default configureStore({\n\u00a0\u00a0reducer: {\n\u00a0\u00a0\u00a0\u00a0users,\n\u00a0\u00a0},\n});\n<\/pre>\n\n\n\n<p><strong>Step 3: <\/strong>Now in your main App.js file, you will need to set up the React Redux provider so that the components anywhere in the tree can be connected to the store.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">src\/App.js\n\/\/ Add below lines of code to the top of the file\nimport { Provider } from 'react-redux';\nimport store from '.\/redux';\n\/\/ At the bottom of your file, replace the export default App with the following:\nexport default () => (\n\u00a0\u00a0&lt;Provider store={store}>\n\u00a0\u00a0\u00a0\u00a0&lt;App \/>\n\u00a0\u00a0&lt;\/Provider>\n);\n<\/pre>\n\n\n\n<p><strong>Step 4: <\/strong>Now we will add the UI.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">src\/Header.js\nimport React from 'react';\nimport { connect } from 'react-redux';\nimport logo from '.\/logo.svg';\nimport { Container, Menu, Image } from 'semantic-ui-react';\nconst Header = ({ pageName }) => (\n\u00a0\u00a0&lt;Menu fixed=\"top\" inverted>\n\u00a0\u00a0\u00a0\u00a0&lt;Container>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;Menu.Item header>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;Image size=\"mini\" src={logo} \/>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0User Search\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;\/Menu.Item>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;Menu.Item style={{ flex: 1 }}>{pageName}&lt;\/Menu.Item>\n\u00a0\u00a0\u00a0\u00a0&lt;\/Container>\n\u00a0\u00a0&lt;\/Menu>\n);\nconst mapStateToProps = state => ({\n\u00a0\u00a0pageName: state.users.selected ? state.users.selected.name : '',\n});\nexport default connect(mapStateToProps)(Header);\n<\/pre>\n\n\n\n<p><strong>Step 5: <\/strong>Next create the search component:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">src\/Search.js\nimport React from 'react';\nimport { connect } from 'react-redux';\nimport { Container, Search } from 'semantic-ui-react';\nimport Fuse from 'fuse.js';\nimport { selectUser } from '.\/users';\nconst SearchPage = ({ users, selectUser }) => {\n\u00a0\u00a0const [term, setTerm] = React.useState('');\n\u00a0\u00a0const filteredUsers = React.useMemo(() => {\n\u00a0\u00a0\u00a0\u00a0if (!term) return users;\n\u00a0\u00a0\u00a0\u00a0const fuse = new Fuse(users, {\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0shouldSort: true,\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0keys: ['name', 'username'],\n\u00a0\u00a0\u00a0\u00a0});\n\u00a0\u00a0\u00a0\u00a0return fuse.search(term);\n\u00a0\u00a0}, [users, term]);\n\u00a0\u00a0return (\n\u00a0\u00a0\u00a0\u00a0&lt;Container>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;Search\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0onResultSelect={(e, { result }) => {\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0setTerm('');\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0selectUser(result.user);\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}}\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0onSearchChange={e => setTerm(e.currentTarget.value)}\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0results={filteredUsers.slice(0, 5).map(user => ({\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0childKey: user.id,\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0title: user.name,\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0description: user.username,\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0image: user.avatar,\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0user,\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}))}\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0value={term}\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\/>\n\u00a0\u00a0\u00a0\u00a0&lt;\/Container>\n\u00a0\u00a0);\n};\nconst mapStateToProps = state => ({\n\u00a0\u00a0users: state.users.users,\n});\nconst mapDispatchToProps = { selectUser };\nexport default connect(\n\u00a0\u00a0mapStateToProps,\n\u00a0\u00a0mapDispatchToProps,\n)(SearchPage);\n<\/pre>\n\n\n\n<p><strong>Step 6: <\/strong>Next, create a component to display the selected user:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">src\/SelectedUser.js\nimport React from 'react';\nimport { connect } from 'react-redux';\nimport { Message, Card, Image } from 'semantic-ui-react';\nimport { selectUser } from '.\/users';\nconst SelectedUser = ({ selected, selectUser }) => {\n\u00a0\u00a0if (!selected) return null;\n\u00a0\u00a0return (\n\u00a0\u00a0\u00a0\u00a0&lt;Card style={{ marginTop: '2em' }}>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;Message\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0attached\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0header={selected.name}\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0onDismiss={() => selectUser(null)}\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\/>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;Image src={selected.avatar} wrapped ui={false} \/>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;Card.Content>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;Card.Header>{selected.username}&lt;\/Card.Header>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;\/Card.Content>\n\u00a0\u00a0\u00a0\u00a0&lt;\/Card>\n\u00a0\u00a0);\n};\nconst mapStateToProps = state => ({\n\u00a0\u00a0selected: state.users.selected,\n});\nconst mapDispatchToProps = { selectUser };\nexport default connect(\n\u00a0\u00a0mapStateToProps,\n\u00a0\u00a0mapDispatchToProps,\n)(SelectedUser);\n<\/pre>\n\n\n\n<p><strong>Step 7: <\/strong>In your src\/index.js file, replace the .\/index.css import content with the Semantic UI css.<\/p>\n\n\n\n<p>import &#8216;semantic-ui-css\/semantic.min.css&#8217;;<\/p>\n\n\n\n<p>Your App.js file will now need to reference the new components you just made. Your App.js file should look like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">src\/App.js\nimport React from 'react';\nimport { Provider } from 'react-redux';\nimport { Container } from 'semantic-ui-react';\nimport store from '.\/redux';\nimport Header from '.\/Header';\nimport Search from '.\/Search';\nimport SelectedUser from '.\/SelectedUser';\nconst App = () => (\n\u00a0\u00a0&lt;div>\n\u00a0\u00a0\u00a0\u00a0&lt;Header \/>\n\u00a0\u00a0\u00a0\u00a0&lt;Container style={{ paddingTop: '7em' }}>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;Search \/>\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0&lt;SelectedUser \/>\n\u00a0\u00a0\u00a0\u00a0&lt;\/Container>\n\u00a0\u00a0&lt;\/div>\n);\nexport default () => (\n\u00a0\u00a0&lt;Provider store={store}>\n\u00a0\u00a0\u00a0\u00a0&lt;App \/>\n\u00a0\u00a0&lt;\/Provider>\n);\n<\/pre>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Redux is a predictable state container for creating JavaScript applications. It helps you in writing applications that behave consistently, run in different environments (client, server, and native), and are easy to test. You can say that Redux is a state management tool. The way Redux works is simple. A central store holds the entire state [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":8340,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[42],"tags":[],"class_list":["post-8338","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-tutorials"],"_links":{"self":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/8338","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/comments?post=8338"}],"version-history":[{"count":0,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/8338\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media\/8340"}],"wp:attachment":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media?parent=8338"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/categories?post=8338"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/tags?post=8338"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}