<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ahsan Ihsan</title>
    <description>The latest articles on DEV Community by Ahsan Ihsan (@ahsanihsan).</description>
    <link>https://dev.to/ahsanihsan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F546498%2F6c95bf37-a6b2-4777-b0ad-aca2cb0238cd.png</url>
      <title>DEV Community: Ahsan Ihsan</title>
      <link>https://dev.to/ahsanihsan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ahsanihsan"/>
    <language>en</language>
    <item>
      <title>How to add redux-persist in your react/react-native application</title>
      <dc:creator>Ahsan Ihsan</dc:creator>
      <pubDate>Thu, 07 Oct 2021 22:36:33 +0000</pubDate>
      <link>https://dev.to/ahsanihsan/how-to-add-redux-persist-in-your-react-react-native-application-4i4f</link>
      <guid>https://dev.to/ahsanihsan/how-to-add-redux-persist-in-your-react-react-native-application-4i4f</guid>
      <description>&lt;p&gt;After adding redux in our applications. We mostly come accross the problem of data being wiped once the browser tab is refreshed. &lt;/p&gt;

&lt;p&gt;To our help we have &lt;a href="https://www.npmjs.com/package/redux-persist"&gt;redux-persist&lt;/a&gt; library which helps us persisting the data of our store even after the web page is closed or refreshed.&lt;/p&gt;

&lt;p&gt;It's very simple to add &lt;code&gt;redux-persist&lt;/code&gt; in our application that uses &lt;code&gt;redux&lt;/code&gt; already.&lt;/p&gt;

&lt;p&gt;Once you setup your redux this is how typically you configure redux store inside your application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

// Redux Imports
import { Provider } from "react-redux";
import Reducer from "./Redux/Reducer";
import { createStore } from "redux";

const store = createStore(Reducer);

function App() {
  return (
    &amp;lt;Provider store={store}&amp;gt;
    &amp;lt;/Provider&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Step 1: Install Redux Persist &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can install &lt;code&gt;redux-persist&lt;/code&gt; using &lt;/p&gt;

&lt;p&gt;&lt;code&gt;yarn install redux-persist&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;OR&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install redux-persist&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;After that we need to do the following imports from &lt;code&gt;redux-persist&lt;/code&gt; library that you just installed.&lt;br&gt;
You have to import them inside the component where you are initialising your redux store.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { persistStore, persistReducer } from "redux-persist";
import { PersistGate } from "redux-persist/integration/react";
import storage from "redux-persist/lib/storage";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After that we have to define the configuration for redux persist store&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const persistConfig = {
  key: "root",
  storage,
};

const persistedReducer = persistReducer(persistConfig, Reducer);

const store = createStore(persistedReducer);
let persistor = persistStore(store);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After adding the above code snippet all you need to do is, to wrap your component inside &lt;code&gt;PersistGate&lt;/code&gt; which helps in delaying the rendering of our app's UI until your persisted state has been retrieved and saved to redux.&lt;/p&gt;

&lt;p&gt;Our final code for &lt;code&gt;App.js&lt;/code&gt; or any file where you are initialising your store is gonna look like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

// Redux Imports
import { Provider } from "react-redux";
import Reducer from "./Redux/Reducer";
import { createStore } from "redux";

// Components import
import ListTodos from "./Screen/ListTodos";

// Redux Persist
import { persistStore, persistReducer } from "redux-persist";
import { PersistGate } from "redux-persist/integration/react";
import storage from "redux-persist/lib/storage";

const persistConfig = {
  key: "root",
  storage,
};

const persistedReducer = persistReducer(persistConfig, Reducer);

const store = createStore(persistedReducer);
let persistor = persistStore(store);

function App() {
  return (
    &amp;lt;Provider store={store}&amp;gt;
      &amp;lt;PersistGate loading={null} persistor={persistor}&amp;gt;
        &amp;lt;ListTodos /&amp;gt;
      &amp;lt;/PersistGate&amp;gt;
    &amp;lt;/Provider&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And voila, you have your redux-persist settled in your application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ahsanihsan/redux-tutorial"&gt;Here's&lt;/a&gt; is a working Todo Application that uses redux persist to store Todos.&lt;/p&gt;

&lt;p&gt;For further explanation we can talk about what those different methods are doing in above code snippets.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;persistStore()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;persistStore method accept a store parameter which is going to be the store that it's gonna persist. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;persistReducer()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In persistReducer method you have to pass the config of persist and the reducer that you created so it helps the package to load the data and initialise the actual redux store.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;PersistGate&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;PersistGate component accepts the persistStore() as a prop and it wraps our application code inside of it which helps in delaying the rendering of our app's UI until the persisted state has been retrieved and saved to redux. It also provides a &lt;code&gt;loading&lt;/code&gt; prop which can show any component such as an Activity Indicator to tell the user that the data is being loaded.&lt;/p&gt;

</description>
      <category>reactnative</category>
      <category>react</category>
      <category>javascript</category>
      <category>redux</category>
    </item>
    <item>
      <title>Learning Redux - Friendly for Beginners</title>
      <dc:creator>Ahsan Ihsan</dc:creator>
      <pubDate>Thu, 07 Oct 2021 22:01:40 +0000</pubDate>
      <link>https://dev.to/ahsanihsan/learning-redux-friendly-for-beginners-485c</link>
      <guid>https://dev.to/ahsanihsan/learning-redux-friendly-for-beginners-485c</guid>
      <description>&lt;p&gt;When I started learning Redux, there were very less resources on the web for beginners with less complication and more demonstration to show how Redux works and what is the easiest way to understand the flow of Redux. This article would help you understand both, the theoretical and the practical part of Redux.&lt;/p&gt;

&lt;p&gt;We will be using the following packages to look at how Redux work with ReactJS, it is same on React Native as well.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;ReactJS app created with CRA&lt;/li&gt;
&lt;li&gt;React Redux&lt;/li&gt;
&lt;li&gt;React Router&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Theoretical Part&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are three main things that you need to understand about redux&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Store&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consider store as a local storage but fast. The data fetching and storing is so fast and it's not asynchronous that's why redux is so fast and responsive.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Actions&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Actions are just like methods. Major portion of logic building is done in action and you can also use different middle-wares for async requests etc. After that, the action tells the reducer to do something with the data.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Reducer&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Reducer is a function that can be called as a decision maker. Action tells the reducer what to do, after the decision reducer changed the state of the store and returns the new one.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2cicplnZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96xpgecrq0z3xgwyj0l5.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2cicplnZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96xpgecrq0z3xgwyj0l5.gif" alt="Data Flow"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Looking at the image above, you can somehow get the idea of how the data is being passed on to the component.&lt;/p&gt;

&lt;p&gt;We can start with the View which is the component you want the data in. You are going to call an action which will perform all the instruction you wrote in it.&lt;/p&gt;

&lt;p&gt;Later on, it will dispatch the action and the reducer inside the store will decide what to do with the action that was dispatched. Now the reducer executes the condition that satisfies the type of action that was dispatched before, and the reducer will then change the old state of the store and return the new one to the component via props.&lt;/p&gt;

&lt;p&gt;We will discuss how the things are working using the props in our practical portion using code snippets, so it becomes more clear!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Practical Part&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Practical Part&lt;/p&gt;

&lt;p&gt;For the practical portion we will be creating a very simple todo application like this &lt;a href="https://todosredux.herokuapp.com/"&gt;Link&lt;/a&gt; that will perform a CRUD operation on redux store. To start we will initialise the store first in our application which is created using Create React Application.&lt;/p&gt;

&lt;p&gt;You would have to install react-redux package in your project using npm or yarn.&lt;/p&gt;

&lt;p&gt;For yarn you can use&lt;/p&gt;

&lt;p&gt;&lt;code&gt;yarn add react-redux&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;For npm you can use&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install react-redux&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We will also be using a middleware to persist the data in store which is optional. Upon refresh it will preserve the previous state of the redux store and your data will not go away!&lt;/p&gt;

&lt;p&gt;To setup the store we will use the App.js and following code snippet which is self explanatory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
import "antd/dist/antd.css";
import "./index.css";

// Redux Imports
import { Provider } from "react-redux";
import Reducer from "./Redux/Reducer";
import { createStore } from "redux";

// Components import
import ListTodos from "./Screen/ListTodos";

const store = createStore(Reducer);

function App() {
  return (
    &amp;lt;Provider store={store}&amp;gt;
      &amp;lt;ListTodos /&amp;gt;
    &amp;lt;/Provider&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above snippet you can see that we are using a &lt;code&gt;createStore()&lt;/code&gt; method from redux and passed on to the Provider component. Provider components makes the Redux store available to all the nested components inside the application. &lt;/p&gt;

&lt;p&gt;Inside the Provider component we can write the rest of the code for the application such as routing etc.&lt;/p&gt;

&lt;p&gt;Now we have 2 steps to complete the setup of redux&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Reducers&lt;/li&gt;
&lt;li&gt;Actions&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Reducer is where the structure of our entities will be defined. Following snippet shows how a reducer is defined:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {
  DELETE_A_TODO,
  ADD_A_TODO,
  MARK_TODO_STATUS,
} from "../../Constants/Todos";

const initialState = {
  todosList: [],
};

function todosReducer(state = initialState, action) {
  if (action.type === ADD_A_TODO) {
    return {
      ...state,
      todosList: [action.payload, ...state.todosList],
    };
  }
  if (action.type === MARK_TODO_STATUS) {
    let newObject = [...state.todosList];
    newObject[action.payload.index].status = action.payload.status;
    return {
      ...state,
      todosList: newObject,
    };
  }
  if (action.type === DELETE_A_TODO) {
    let newObject = [...state.todosList];
    let index = newObject.findIndex((item) =&amp;gt; {
      return item.key === action.payload;
    });
    newObject.splice(index, 1);
    return {
      ...state, 
      todosList: newObject,
    };
  }
  return state;
}

export default todosReducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see that the reducer is just a function with conditions inside, that will conclude what type of action is to be performed.&lt;/p&gt;

&lt;p&gt;But, if you look at the top. We have the initial value of the store which is just an array of &lt;code&gt;todosList: []&lt;/code&gt; where we will be storing our todos and performing CRUD operations on.&lt;/p&gt;

&lt;p&gt;That is all you need to focus on right now. Once we call different actions. We will look at how the dispatched action is being processed inside the reducer.&lt;/p&gt;

&lt;p&gt;Next up, we will be setting our actions. We will have only three actions in our small application.&lt;/p&gt;

&lt;p&gt;1) Add a todo&lt;br&gt;
2) Mark todo status (Done, Pending)&lt;br&gt;
3) Delete a todo&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {
  ADD_A_TODO,
  MARK_TODO_STATUS,
  DELETE_A_TODO,
} from "../Constants/Todos";

export const addATodo = (todo) =&amp;gt; {
  return {
    type: ADD_A_TODO,
    payload: todo,
  };
};

export const deleteATodo = (key) =&amp;gt; {
  return {
    type: DELETE_A_TODO,
    payload: key,
  };
};

export const markTodoStatus = (data) =&amp;gt; {
  return { type: MARK_TODO_STATUS, payload: data };
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The actions above are methods that are returning plain objects. Once the action is dispatched by the component. It goes to the reducer with the type of reducer.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What is type of the action?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I have declared constants of plain strings to keep the code clean. They are just unique strings so the reducer can identify what type of action is dispatched.&lt;/p&gt;

&lt;p&gt;Then, there is a payload key using which you can send any kind of data to the reducer. You can also process the data before sending it to the reducer inside the action. And you can also do the minor customisation of the data inside the reducer. We will be going with the latter one and process the data inside the reducer as they are just minor tasks that will be performed on the todoList inside the reducer state.&lt;/p&gt;

&lt;p&gt;We will move on to the main portion, as the setup for the Redux flow is complete. All you need to do is to dispatch the action and redux will do the magic for you!&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Dispatching actions inside a view&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Before moving towards the code side. We have to discuss three methods&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;connect()()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Connect method is provide by react-redux package which allows you to connect any component with the redux tree. So you can have access to the state and dispatch method. You have to pass 2 objects mapDispatchToProps, mapStateToProps which we will talk about later in the next point. And we have to pass the Component that we are working on.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;mapDispatchToProps&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;mapDispatchToProps is a plain object in which you pass the actions that you created. And connect will attach the dispatch method with those actions so you can dispatch the actions. The actions will then be accessible via props of the component you passed inside the connect method.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;mapStateToProps&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;mapStateToProps is a method that receives a callback param using which you can access the current state of the entire store. And you can access only the keys of the store that you need inside the function and return it. Once done, those keys will be accessible inside the component via props.&lt;/p&gt;

&lt;p&gt;The snippet below shows how connect uses the component and uses mapDispatchToProps and mapStateToProps to map the state and actions with the component you are in.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mapDispatchToProps = {
  markTodoStatus,
  addATodo,
  deleteATodo,
};

const mapStateToProps = (state) =&amp;gt; {
  return {
    todos: state.todos.todosList,
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(ListTodos);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;mapDispatchToProps&lt;/code&gt; is just accepting the actions that we created and sending inside the connect method which will be later accessible inside the component &lt;code&gt;ListTodos&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;mapStateToProps is just accepting the current state of the store and only getting the &lt;code&gt;todosList&lt;/code&gt; from the reducer &lt;code&gt;todos&lt;/code&gt; and returning that inside an object. Which will also be later accessible inside the component.&lt;/p&gt;

&lt;p&gt;Now, this is where the real magic happens. Wherever you are inside the hierarchy of your code. All you need to do is to connect any component with redux and you can utilise the data or change the data anywhere inside the application. That's how the state becomes so easy to manage inside a React app using Redux.&lt;/p&gt;

&lt;p&gt;Last but not least, we need to discuss how we are managing the data inside the reducer that is passed when any action is dispatched. We will follow the whole hierarchy of how the method is dispatched inside the component.&lt;/p&gt;

&lt;p&gt;After using &lt;code&gt;dispatchToProps&lt;/code&gt; parameter in &lt;code&gt;connect()()&lt;/code&gt; method. We will have access to any action that was passed inside &lt;code&gt;dispatchToProps&lt;/code&gt; object. Now you can access that particular action inside your component and call it using&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;props.addATodo({
  key: props.todos.length,
  task: "Do Something",
  status: false,
  priority: "Important",
};)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the action is called using the above code snippet it goes to the reducer and looks at what type of action is performed. If you look at the actions we defined we have &lt;code&gt;addATodo&lt;/code&gt; action inside our &lt;code&gt;action.js&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const addATodo = (todo) =&amp;gt; {
  return {
    type: ADD_A_TODO,
    payload: todo,
  };
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once it's dispatched the whole flow is shifted towards the reducer. Reducer then looks at what type of action was dispatched and it changes the state of redux store accordingly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (action.type === ADD_A_TODO) {
  return {
    ...state,
    todosList: [action.payload, ...state.todosList],
  };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we have wrote the instructions to append the payload sent by the action inside the previous state of the store.&lt;/p&gt;

&lt;p&gt;After that you will see that the data will be available in TodoList component. For testing you can place some &lt;code&gt;console.log()&lt;/code&gt; to see how the data is being passed and ends up inside the component. After that if you try to access that data in any component and use &lt;code&gt;mapStateToProps&lt;/code&gt; method. It will return you data even if that component is nested 10 times deep down the hierarchy!&lt;/p&gt;

&lt;p&gt;By this you will get the idea of how the data flow of a very simple application is being controlled. You can have a look at the code the GitHub repository link is here &lt;a href="https://github.com/ahsanihsan/redux-tutorial"&gt;Link&lt;/a&gt;. Fire up the repository code by running &lt;code&gt;yarn install&lt;/code&gt; or &lt;code&gt;npm install&lt;/code&gt; and see the application in action. You can use this concept to map it in your applications and make your state management easier.&lt;/p&gt;

&lt;p&gt;Last we will be looking at how we can implement the redux persist middleware to make sure once the browser screen is refreshed. The data is not lost and it stays in your application.&lt;/p&gt;

&lt;p&gt;Here is the link to &lt;a href="https://dev.to/ahsanihsan/how-to-add-redux-persist-in-your-react-react-native-application-4i4f"&gt;How to add redux-persist in your react/react-native application&lt;/a&gt;&lt;/p&gt;

</description>
      <category>redux</category>
      <category>javascript</category>
      <category>react</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
