<?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[Super-coder - Medium]]></title>
        <description><![CDATA[Learn useful tips about front-end web development. - Medium]]></description>
        <link>https://medium.com/super-coder?source=rss----6da59f575e69---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Super-coder - Medium</title>
            <link>https://medium.com/super-coder?source=rss----6da59f575e69---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:16:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/super-coder" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Adding Notifications to your React Website]]></title>
            <link>https://medium.com/super-coder/adding-notifications-to-your-react-website-e52a1975610d?source=rss----6da59f575e69---4</link>
            <guid isPermaLink="false">https://medium.com/p/e52a1975610d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Eduardo Valencia]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 02:11:01 GMT</pubDate>
            <atom:updated>2020-07-06T02:11:01.111Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*PHsZ4UKNSMHDrtMf6O3bew.png" /></figure><p>Has a website ever asked you if you want to receive notifications? Some websites, such as Reddit, use notifications to inform you of new content. In this article, I will show you how to add notifications to a React application. I will explain how the browser sends notifications, how to add authentication, and how service workers show notifications. First, I will explain a few concepts.</p><p>The Push API helps you trigger notifications. Specifically, the server (back-end) will trigger a notification and send a signal to the front-end, called a <em>push</em> event. Once the front-end application receives this signal, it can display a notification. Before sending a push event, however, the application must identify who to send it to. This is what subscriptions are for.</p><p>Using subscriptions, applications can send notifications to specific people. Similar to how addresses tell the postal service where to deliver a package, subscriptions tell apps where to deliver a notification. To use subscriptions, your application must do the following:</p><ol><li>Front-end must create a subscription and send it to the server.</li><li>The server must save the subscription.</li><li>The server uses it to create a push event.</li></ol><p>By creating subscriptions, your application can send notifications to users.</p><p>What if someone stole that subscription? Without authentication, hackers could send users harmful notifications. This is where VAPID comes in. The <strong>Voluntary Application Server Identification</strong> protocol allows the front-end to verify that notifications come from the correct sender. If authentication fails, your application will not display a notification. When you use VAPID, you must create a key pair: a private key and a public key. As the names imply, a <strong>private key</strong> should never be shared and is stored in the server, while a <strong>public key</strong> is public and is given to the front-end application. Using VAPID, we can send notifications securely.</p><p>The final concept you must understand is how service workers are involved in displaying notifications. As I have explained, the front-end must listen to a signal called a <em>push</em> event to display a notification. This is done inside of the service worker, and I will leave an example below:</p><pre>const handlePush = event =&gt; {<br>  const options = {<br>    body: &#39;This is the body of the notification.&#39;,<br>  }<br><br>  event.waitUntil(<br>    self.registration.showNotification(&#39;Title&#39;, options)<br>  )<br>}<br><br>self.addEventListener(&#39;push&#39;, handlePush)</pre><p>As you can see above, you must add an event listener for the push event. To show the notification, you must use self.registration.showNotification. You can provide a title and options, too. Once the service worker receives the push event, it will display a notification. Let’s put these ideas into practice by adding a reminders feature to a to-do list application.</p><h4>Download the New Project</h4><p>To show notifications, you need a back-end. Since you are a front-end developer, I have already created a back-end for you. Download the project files by running the following commands:</p><pre>git clone https://github.com/eduardo-valencia/progressive-blog-example.git<br>cd progressive-blog-example<br>git checkout tasks<br>git checkout 95d2c2a6d9ada4de700be0e5cf9f45270dbaa002</pre><p>Then, install the packages for both the server and the front-end:</p><pre>npm install<br>cd server<br>npm install express web-push axios node-schedule<br>cd ..</pre><p>If you are following along, you should note that I made a few changes to the service worker so that it works in both development and production. Notice that I added a new file, service-worker-src.js, inside of the public folder. As the name implies, this is where you will make changes to edit the service worker.</p><p>Also, I modified the config-overrides.js file. Take a look at it below:</p><pre>const { join } = require(&#39;path&#39;)<br>const { InjectManifest } = require(&#39;workbox-webpack-plugin&#39;)<br>const { env } = require(&#39;process&#39;)<br><br>const getPublicPath = (subPath) =&gt; join(__dirname, &#39;public&#39;, subPath)<br><br>const getPluginConfig = () =&gt; {<br>  const baseConfig = {<br>    swSrc: getPublicPath(&#39;service-worker-src.js&#39;),<br>    maximumFileSizeToCacheInBytes: 100 * 1024 * 1024,<br>  }<br>  if (env.NODE_ENV === &#39;production&#39;) {<br>    return {<br>      ...baseConfig,<br>      swDest: getPublicPath(&#39;service-worker.js&#39;),<br>      include: [/\.svg$/, /\.html$/, /\.css$/, /\.js$/],<br>    }<br>  }<br>  return baseConfig<br>}<br><br>const getInjectManifestPlugin = () =&gt; {<br>  const config = getPluginConfig()<br>  return new InjectManifest(config)<br>}<br><br>const getWebpackConfig = (config) =&gt; {<br>  const configuredPlugin = getInjectManifestPlugin()<br>  return {<br>    ...config,<br>    plugins: [...config.plugins, configuredPlugin],<br>  }<br>}<br><br>module.exports = {<br>  webpack: getWebpackConfig,<br>}</pre><p>There are a few important differences between the previous file and this new one. One of the app’s dependencies, workbox-webpack-plugin, has a bug that prevents the app from precaching files correctly in development mode. Therefore, the app now only precaches files in production. Also, it will use the service-worker-src.js as the service worker file in development, but will use the service-worker.js file in production. This will help stop any precaching issues. Now we can begin adding the reminders feature.</p><h4>Creating Reminders</h4><p>In our application, we will add reminders to tasks. Users will be able to click on a task to set a reminder with a date and time. Once the application is finished, users will receive notifications in their browser, even if the application is closed. To add this feature, we must complete the following steps in the front-end:</p><ol><li>Create a component that lets users choose when to receive a reminder</li><li>Ask users for permission to send notifications</li><li>Create and store a subscription</li><li>Listen for the push event in the service worker</li><li>Show a notification whenever we receive a push event</li></ol><p>First, we will create the component that allows users to set reminders. Go to the src/components/Tasks/Task/index.js file and replace everything inside with the following code:</p><pre>import React, { Component } from &#39;react&#39;<br>import Checkbox from &#39;./Checkbox&#39;<br>import Modal from &#39;./Modal&#39;<br><br>export class Task extends Component {<br>  render() {<br>    const { id, title } = this.props<br>    const modalId = `modal-${id}`<br>    return (<br>      &lt;&gt;<br>        &lt;Modal id={modalId} /&gt;<br>        &lt;div className=&quot;card my-3&quot;&gt;<br>          &lt;div className=&quot;card-body d-flex align-items-center&quot;&gt;<br>            &lt;Checkbox task={this.props} /&gt;<br>            &lt;button<br>              className=&quot;btn btn-link&quot;<br>              data-target={`#${modalId}`}<br>              data-toggle=&quot;modal&quot;<br>            &gt;<br>              &lt;h5 className=&quot;card-title text-body&quot;&gt;{title}&lt;/h5&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/&gt;<br>    )<br>  }<br>}<br><br>export default Task</pre><p>This will open a modal whenever the name of a task is clicked on. Notice how it imports a component named Modal. To add this component, create a new directory named Modal and create a file called index.js inside it. Add the following code:</p><pre>import BaseModal from &#39;../../../shared/Modal&#39;<br>import React, { Component } from &#39;react&#39;<br>import Close from &#39;../../../shared/Close&#39;<br>import Permission from &#39;./Permission&#39;<br>import Schedule from &#39;./Schedule&#39;<br>import axios from &#39;axios&#39;<br><br>export class Modal extends Component {<br>  render() {<br>    const { id } = this.props<br>    return (<br>      &lt;BaseModal id={id} footer={&lt;Close /&gt;} title=&quot;Schedule Reminder&quot;&gt;<br>      &lt;/BaseModal&gt;<br>    )<br>  }<br>}<br><br>export default Modal</pre><p>Inside of this modal, we will ask users if they want to receive notifications. Currently, the modal is empty, but we will add more to it later.</p><p>After the user gives us permission to show notifications, we will store a subscription inside of the database. The following is an example of a subscription:</p><pre>{<br>    &quot;endpoint&quot;: &quot;https://fcm.googleapis.com/fcm/send/...&quot;,<br>    &quot;expirationTime&quot;: null,<br>    &quot;keys&quot;: {<br>      &quot;p256dh&quot;: &quot;...&quot;,<br>      &quot;auth&quot;: &quot;...&quot;<br>    }<br>}</pre><p>The subscription contains the information the app needs to send a notification to a specific user. Next, I will explain the steps to create a subscription.</p><p>Before asking users for permission, we must verify that their browser supports notifications. Although most modern browsers support notifications, some browsers (including iOS Safari) do not. Therefore, we must check if the browser supports notifications using the following code:</p><pre>if (&#39;serviceWorker&#39; in navigator &amp;&amp; &#39;Notification&#39; in window) {<br>  // Use notification features here...<br>}</pre><p>After we check if the browser supports notifications, we can request permission to show them. Copy and paste the following method inside of the Modal component:</p><pre>requestPermission = async () =&gt; {<br>  if (&#39;serviceWorker&#39; in navigator &amp;&amp; &#39;Notification&#39; in window) {<br>    await Notification.requestPermission()<br>    // We will create this method next.<br>    await this.getAndSaveSubscription()<br>  }<br>}</pre><p>Notice how we only use the Notication.requestPermission method after checking if the browser supports notifications. After calling this method, the browser will show an alert asking if the user wants to block or allow notifications from our application. Next, we will create a subscription.</p><h4>Authentication</h4><p>After we get permission from the user, we must create a subscription so that the server can send notifications to the user. To send notifications securely, we must use authentication when creating the subscription.</p><p>To authenticate our application, you will need to create two keys:</p><ol><li>A private key</li><li>A public key</li></ol><p>The keys.js file will create our keys. In your terminal, type in the following command to generate your keys:</p><pre>node server/src/keys.js</pre><p>This will generate two keys:</p><pre>publicKey 8r2LGw39bNew49eTYPgWaPUYDyqolMI<br>privateKey k8VbeUNiGVnSQuqUVUVlF2HZzhQSfc4N44gXcud</pre><p>The first one is your public key, and the second is your private key. You should store both in your server as environment variables. Open the server/.env file and add <em>your</em> keys like in the following example:</p><pre>PUBLIC_KEY=&quot;your public key goes here&quot;<br>PRIVATE_KEY=&quot;your private key goes here&quot;</pre><p>If you have not worked with environment variables before, notice that the variable names must be uppercase, while values should be encased with quotes.</p><p>You must also add your <strong>public</strong> key to your React app. Open the other .env file in the root of the project directory, and add your private key like in the following example:</p><pre>REACT_APP_PUBLIC_KEY=&quot;your public key goes here&quot;</pre><p>Notice that you must prepend your variable names with REACT_APP_. Great! You are now ready to create the subscription.</p><h4>Creating the Subscription</h4><p>To create the subscription, you must use the service worker’s registration pushManager.subscribe method, which takes a few options. One of the required options is applicationServerKey, which is the public key that we just added as an environment variable, but in the form of a “UInt8” array. To convert the public key to a UInt8 array, you will need some code from the web-push library. Inside the utils/base64.js file, there is a function named urlBase64ToUint8Array from the web-push library, and it will convert the public key to the “Uint8Array.” Next, you will use it.</p><p>Inside of the src/components/Tasks/Task/Modal/index.js file, import the aforementioned function at the top of the file:</p><pre>import { urlBase64ToUint8Array } from &#39;../../../../utils/base64&#39;</pre><p>Inside of the Modal component, add the following method to convert the public key from your environment variables into a “Uint8Array.”</p><pre>getApplicationKey = () =&gt; {<br>  const { REACT_APP_PUBLIC_KEY } = process.env<br>  return urlBase64ToUint8Array(REACT_APP_PUBLIC_KEY)<br>}</pre><p>This method gets the environment variable that you added in the .env file, converts it into a “Uint8Array,” and returns it.</p><p>Finally, we can create a subscription. Add the following method to the Modal component:</p><pre>getSubscription = async () =&gt; {<br>  const registration = await navigator.serviceWorker.getRegistration()<br>  return registration.pushManager.subscribe({<br>    userVisibleOnly: true,<br>    applicationServerKey: this.getApplicationKey(),<br>  })<br>}</pre><p>First, we get the service worker registration, which has the pushManager.subscribe method. Then, we pass two options: userVisibleOnly and applicationServerKey. To get the application server key, we call the method that we created earlier. Finally, we return the result. Great! We now have a subscription that identifies each user. Next, we will save it so that the server can access it.</p><p>To save the subscription in the database, we must make a POST request to the API. Copy and paste the following code to save the subscription:</p><pre>state = {<br>  subscription: null,<br>}<br><br>setSubscription = (subscription) =&gt; this.setState({ subscription })<br><br>saveSubscription = (subscription) =&gt;<br>  axios.post(&#39;/api/subscription&#39;, subscription)<br><br>getAndSaveSubscription = async () =&gt; {<br>  const subscription = await this.getSubscription()<br>  await this.saveSubscription(subscription)<br>  this.setSubscription(subscription)<br>}</pre><p>First, it gets the subscription using the getSubscription method we created earlier. Then, it sends a POST request to the API to save the subscription in the database. Finally, it updates the Modal’s state to reflect that the user now has a subscription. The server can now use the subscription to send a notification.</p><p>What if the user already has a subscription? Currently, the application will ask the user if they want to receive notifications even if they already have a subscription. To prevent this, we will check if the user already has a subscription by using the service worker’s getSubscription method. Copy and paste the following methods inside of the Modal component.</p><pre>getIfHasSubscription = async () =&gt; {<br>  if (&#39;serviceWorker&#39; in navigator) {<br>    const registration = await navigator.serviceWorker.ready<br>    return registration &amp;&amp; registration.pushManager.getSubscription()<br>  }<br>  return false<br>}<br><br>getAndSetSubscription = async () =&gt; {<br>  const subscription = await this.getIfHasSubscription()<br>  this.setSubscription(subscription)<br>}<br><br>async componentDidMount() {<br>  await this.getAndSetSubscription()<br>}</pre><p>The following happens in this code:</p><ol><li>It gets the service worker registration</li><li>It uses the registration to get a subscription (if any)</li><li>The getSubscription method returns null or a subscription depending on whether the subscription exists.</li><li>It updates the Modal’s state with the subscription.</li></ol><h4>Creating the Schedule Component</h4><p>Now we can use the subscription in the state to ask users if they want to receive notifications. To do this, we must create a component that asks users for permission. First, create a new file called Permission.js in the Modal folder, and copy and paste the following code:</p><pre>import React, { Component } from &#39;react&#39;<br><br>export class Permission extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h4&gt;Please enable notifications.&lt;/h4&gt;<br>        &lt;p&gt;<br>          To use reminders, you must enable notifications. Click &quot;Enable<br>          Notifications&quot; below to continue.<br>        &lt;/p&gt;<br>        &lt;button<br>          className=&quot;btn btn-primary&quot;<br>          onClick={this.props.requestPermission}<br>        &gt;<br>          Enable Notifications<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}<br><br>export default Permission</pre><p>Notice that it calls the this.props.requestPermission method, which we created inside of the Modal component earlier. Whenever users click on the “Enable Notifications” button, the browser will ask them if they want to enable or block notifications.</p><p>Second, you must create the scheduling component. Inside the current folder, create a new folder called Schedule and add a file named index.js inside it. Then, copy and paste the code below.</p><pre>import React, { Component } from &#39;react&#39;<br>import Calendar from &#39;react-calendar&#39;<br>import Time from &#39;./Time&#39;<br>import axios from &#39;axios&#39;<br>import &#39;react-calendar/dist/Calendar.css&#39;<br><br>export class Schedule extends Component {<br>  state = {<br>    date: new Date(),<br>    time: 0,<br>  }<br><br>  setKeyAndValue = (key, value) =&gt;<br>    this.setState((prevState) =&gt; ({ ...prevState, [key]: value }))<br><br>  handleCalendarChange = (date) =&gt; this.setKeyAndValue(&#39;date&#39;, date)<br><br>  handleTimeChange = (event) =&gt; this.setKeyAndValue(&#39;time&#39;, event.target.value)<br><br>  getHoursAndMinutes = () =&gt; {<br>    const { time } = this.state<br>    const match = time.match(/(\d{2}):(\d{2})/)<br>    return {<br>      hours: match[1],<br>      minutes: match[2],<br>    }<br>  }<br><br>  getDateCopy = () =&gt; {<br>    const { date } = this.state<br>    let clone = new Date()<br>    clone.setTime(date.getTime())<br>    return clone<br>  }<br><br>  getDateWithTime = () =&gt; {<br>    const date = this.getDateCopy()<br>    const { hours, minutes } = this.getHoursAndMinutes()<br>    date.setHours(hours)<br>    date.setMinutes(minutes)<br>    return date<br>  }<br><br>  submit = () =&gt; {<br>    const dateWithTime = this.getDateWithTime()<br>    const seconds = dateWithTime.getTime()<br>    return axios.post(&#39;/reminder&#39;, { time: seconds })<br>  }<br><br>  handleClick = this.submit<br><br>  render() {<br>    const { date, time } = this.state<br>    return (<br>      &lt;div&gt;<br>        &lt;Calendar onChange={this.handleCalendarChange} value={date} /&gt;<br>        &lt;Time onChange={this.handleTimeChange} value={time} /&gt;<br>        &lt;div className=&quot;d-block&quot;&gt;<br>          &lt;button className=&quot;btn btn-primary&quot; onClick={this.handleClick}&gt;<br>            Set Reminder<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}<br><br>export default Schedule</pre><p>This component renders a calendar that lets users pick the reminder’s date. Notice that it renders a button with a this.handleClick method. When the user clicks it, it will schedule a reminder based on the date and time the user entered.</p><p>Third, create a component for setting the time. In the same folder, create a new file named Time.js and add the following code:</p><pre>import React, { Component } from &#39;react&#39;<br><br>export class Time extends Component {<br>  render() {<br>    return (<br>      &lt;label className=&quot;mt-3 form-group&quot;&gt;<br>        Select Time<br>        &lt;input type=&quot;time&quot; className=&quot;form-control&quot; {...this.props} /&gt;<br>      &lt;/label&gt;<br>    )<br>  }<br>}<br><br>export default Time</pre><p>As the name suggests, this component lets users schedule a reminder for a specific time. Great! We have now created the components.</p><p>After creating the components, we must decide when to show the Schedule or Permission screen. Recall that we must render the Schedule component if the user allowed us to show notifications, and the Permission component if they have not. Since a subscription is nullwhen the user has not given us permission, we can use the subscription in the state to decide which component to render. Inside the Modal component, replace the render method with the following code:</p><pre>render() {<br>  const { id } = this.props<br>  const { subscription } = this.state<br>  return (<br>    &lt;BaseModal id={id} footer={&lt;Close /&gt;} title=&quot;Schedule Reminder&quot;&gt;<br>      {subscription ? (<br>        &lt;Schedule /&gt;<br>      ) : (<br>        &lt;Permission requestPermission={this.requestPermission} /&gt;<br>      )}<br>    &lt;/BaseModal&gt;<br>  )<br>}</pre><p>If the user has a subscription, then the component will allow them to schedule a reminder. Otherwise, it will ask them to enable notifications. Great! We can now create the event listener in the service worker.</p><h4>Listening for the Push Event</h4><p>The service worker is responsible for listening for the push event and showing notifications. Open the service-worker-src.js file, and copy and paste the following code:</p><pre>const handlePush = (event) =&gt; {<br>  const { data } = event<br>  const options = {<br>    body: data ? data.text() : &#39;This is the body of the notification&#39;,<br>  }<br>  event.waitUntil(self.registration.showNotification(&#39;Reminder!&#39;, options))<br>}<br><br>self.addEventListener(&#39;push&#39;, handlePush)</pre><p>First, the service worker listens for the push event and calls the handlePush function when it receives one. Second, it creates options for the notification, including the notification’s body. Notice that the body is set to data.text(). In this application, the back-end sends data (the notifications’s body) inside of the push event, and we are getting this data using data.text(). Finally, we use the service worker’s registration to show a notification titled “Reminder!” As the final step in this article, we will test our application.</p><h4>Testing the Application</h4><p>To test our application, turn on your server by running npm start in your terminal. After the page loads, you should see a list of tasks.</p><figure><img alt="List of 2 tasks. The first task has a title of “my new task,” and the second is titled “Buy groceries.”" src="https://cdn-images-1.medium.com/max/1024/1*wi5kLFwyJ2UIdeZ2CTczWg.png" /></figure><p>However, you may be viewing a cached version of the page. To get the latest version, close the page and go to http://localhost:3000 again. You should now have the app’s latest version.</p><p>Click on one of the task’s titles. Then, it should display the following screen:</p><figure><img alt="Message asking users to enable notifications. It has a blue button named “Enable Notifications.”" src="https://cdn-images-1.medium.com/max/1024/1*3ll0ZJozTJdiUuO7PqWHww.png" /></figure><p>Click on the button titled “Enable Notifications.” It will show an alert asking whether you want to enable or block notifications. Click “Enable.” Behind the scenes, the application will create a subscription and save it to the database. Then, it will update the component’s state with the new subscription and show the Schedule component. Then, the following screen should show:</p><figure><img alt="The scheduling component. It has a month calendar and a time input. At the bottom, there is a button labeled “Set Reminder.”" src="https://cdn-images-1.medium.com/max/1024/1*5rfnn1_oNn_cxE-l0XwVtA.png" /></figure><p>You should now set the reminder’s time. Click on the time input and enter a time that is a few minutes away from your current time. For example, if it is 5:31 PM, you should choose 5:33 PM.</p><figure><img alt="The time component with “5:33 PM”" src="https://cdn-images-1.medium.com/max/1024/1*zFcXm4b3qNIh1I4Gakpdcg.png" /></figure><p>Finally, click on the “Set Reminder” button. Wait for 2–3 minutes, and you should see the following notification show on screen:</p><figure><img alt="A notification titled “Reminder!” from “localhost:3000.” It has a body of “Test”." src="https://cdn-images-1.medium.com/max/325/1*SabXx6C-4VBt9QMtvIJxdA.png" /></figure><p>It will look different if you are on Windows. If you received the notification, then congratulations! You learned how to add notifications.</p><p>In this article, you learned how to add notifications to React. First, you learned that the Push API is responsible for triggering notifications. Using subscriptions, your application can identify a specific user and send them a notification. Second, you learned why authentication is important and how we can VAPID to authenticate our app. VAPID involves using a pair of private and public keys, and the app uses the public key when creating a subscription. Finally, you learned that the service worker listens for the <em>push</em> event to send notifications. Thank you for reading! Feel free to ask any questions.</p><h3>Resources</h3><p><a href="https://github.com/eduardo-valencia/progressive-blog-example">Project Repository</a></p><p><a href="https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications#subscribing_to_push_notifications">Introduction to Push Notifications</a></p><p><a href="https://github.com/web-push-libs/web-push">Web Push Library</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e52a1975610d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/super-coder/adding-notifications-to-your-react-website-e52a1975610d">Adding Notifications to your React Website</a> was originally published in <a href="https://medium.com/super-coder">Super-coder</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Background Synchronization]]></title>
            <link>https://medium.com/super-coder/background-synchronization-5028080d611e?source=rss----6da59f575e69---4</link>
            <guid isPermaLink="false">https://medium.com/p/5028080d611e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Eduardo Valencia]]></dc:creator>
            <pubDate>Sat, 16 May 2020 01:16:01 GMT</pubDate>
            <atom:updated>2020-05-16T01:16:00.886Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8LK5903Ze_KoPk9sHhlhw.png" /></figure><p>Welcome back! This is my third article in my series of “Progressive Web App” articles. If you have not read my other articles, please read them since they explain the important concepts behind progressive web apps.</p><p><a href="https://supercoder.dev/blog/ae2edc22-61e0-560d-929c-23f69da5867a">Progressive Web Apps and React</a></p><p><a href="https://supercoder.dev/blog/53180140-47d2-5a77-9d65-2319c561ec86">Workbox and Versioning</a></p><p>Imagine that you are sitting on your couch and using Reddit. After a post makes you laugh, you decide to upvote it. Then, you close the app. Wouldn’t it be awful if the upvote did not get sent because you closed the app? This is the problem that background synchronization aims to solve. By using background synchronization, you can make requests even when the browser or page is closed. In this article, I will explain how background synchronization works, how to implement it without Workbox, and how to implement it with Workbox.</p><p>Before we begin, I would like to remind you that you must understand how service workers update. Please visit the article below to learn how.</p><p><a href="https://supercoder.dev/blog/ed66ca43-c5d0-572a-82e0-15f6c48663d8">How Service Workers Update</a></p><h4>New App</h4><p>In the previous section, I used a blog application to demonstrate precaching in Workbox. To help you see background sync in action, I have made a few changes to the previous application. The app is now a to-do app, and you can see the list of tasks on the home page.</p><figure><img alt="The app&#39;s task page. Each task has a checkbox near it." src="https://cdn-images-1.medium.com/max/1024/0*tNjXwhAVMyOwDsQQ.png" /></figure><p>Clicking on the “Add Task” button at the top will let you add a task with a name.</p><figure><img alt="A modal with an input for the task name. It has the &quot;Close&quot; and &quot;Add Task&quot; buttons at the bottom." src="https://cdn-images-1.medium.com/max/1024/0*CgX7cWUYHDTIkI7H.png" /></figure><h4>Installation</h4><p>If you want to follow along and install the app, clone it into a new directory using the following code:</p><pre>git clone https://github.com/eduardo-valencia/progressive-blog-example.git<br>git checkout tasks</pre><p>Then, change into the directory that was created and install all of the dependencies.</p><pre>npm install</pre><p>Finally, run npm start and the app will load.</p><h4>Background Synchronization</h4><figure><img alt="A diagram describing the background synchronization process. Background sync requires registering a tag and creating an event listener. To create a task, the app verifies that the service worker is available. If it is available, then it registers a tag and adds the tasks to the database. In contrast, if it is not available it makes a network request directly to the API. The sync event listener gets an event tag and verifies that it describes adding a task. If it does, then it gets the tasks from the database, creates each of the tasks, and deletes the old tasks." src="https://cdn-images-1.medium.com/max/1024/0*l4Q7B6T5r54rrDVk.png" /></figure><p><strong>Background synchronization</strong> involves postponing a request until the application is back online. Even if the page or browser is closed, the app can make a request once it detects that your phone or computer is back online. How does the application make a request when it is closed? By using a service worker and registering an event listener, you can postpone requests until the application is online.</p><p>Background synchronization involves four main steps.</p><p>First, you must check that service workers are available. This is because service workers are not available on all browsers, such as iOS Safari. You can check whether service workers are available by using the following code:</p><pre>if (navigator.serviceWorker) {<br>  // ...Use background sync<br>}</pre><p>Second, you must tell the app to use background sync by registering a sync tag inside of your main application. A <strong>sync tag</strong> describes the action that you want to take. For example, if you wanted to create a task, you could name the sync tag “addTask.” By registering a sync tag, you are telling the service worker that you have postponed certain requests.</p><p>The following code will provide an example of registering a sync tag:</p><pre>// Inside of your main application.<br><br>const registerTag = async () =&gt; {<br>  // Wait for the service worker.<br>  const registration = await navigator.serviceWorker.ready<br>  // Using the registration, register a tag.<br>  await registration.sync.register(&#39;addTask&#39;)<br>}</pre><p>To register a sync tag, you must first check that the service worker is ready. The app will give you a <strong>registration</strong> once the service worker is ready, and you can use it to register a sync tag. Notice how I used await to get the registration. Then, I used the register method to register a tag with the name of “addTask.” This is the first step in using background synchronization.</p><p>Third, you must use a sync event listener inside of your service worker to detect when the application goes back online. Whenever you register any tag, the sync event listener inside receives the tag once the application is back online. Then, the event listener receives the event’s tag name, which is addTask in the example. The following code shows you how to create a sync event listener.</p><pre>self.addEventListener(&#39;sync&#39;, async (event) =&gt; {<br>  const { tag } = event<br>  if (tag === &#39;addTask&#39;) {<br>    // Do something here...<br>  }<br>})</pre><p>Notice how the event contains the tag property. You should check the name of the tag because you may want to register another tag in the future, and you may want to take different actions for different tags.</p><p>Finally, you should make the requests that you postponed.</p><pre>const addTask = () =&gt; fetch(&#39;/api/task&#39;, { method: &#39;POST&#39; })<br><br>self.addEventListener(&#39;sync&#39;, async (event) =&gt; {<br>  const { tag } = event<br>  if (tag === &#39;addTask&#39;) {<br>    await addTask()<br>  }<br>})</pre><p>Notice how I called the addTask function to make a request. This means that whenever I register the “addTask” tag and the application is online, I will make a request to create a task. However, I do not have enough information to make the request. Specifically, I do not have any data for the request’s body. Usually, you would have this information in the main application. Therefore, I need a way to share information between the main application and the service worker. The solution to this problem is Indexed DB.</p><h4>Indexed DB and Dexie</h4><figure><img alt="A diagram describing how the application&#39;s data is affected. First, the main application adds the task data to Indexed DB. Then, the service workers gets the task data from the database and uses it to create the tasks inside of the API." src="https://cdn-images-1.medium.com/max/1024/0*Re6-vnz7F6P5LloK.png" /></figure><p>To make a request, you may need information that is not available to you from within the service worker. You can use <strong>Indexed DB</strong>, a client-side database, to store information inside of your main app and then access it from within the service worker. A <strong>database</strong> is much like a JavaScript array in that you can add, get, update, or delete specific items. To facilitate the process of using the database, we will install and use a library named “Dexie.”</p><p>Dexie is a library that helps you interact with Indexed DB. To use it, you must create a database with a specific name. Think of this as a folder inside of your computer. Each database can have multiple <strong>tables</strong> (also called “stores”), which are groups of information. Tables are like nested folders inside of the main database folder. Inside of each table, you can create specific <strong>entries</strong>, which are the individual items in the database. An entry is a JavaScript object and can have many properties, such as “name,” “address,” or “email.” Next, I will show you how to install Dexie and create your database.</p><p>Install Dexie now by going inside of the project’s directory and running the following command:</p><pre>npm i dexie</pre><h4>Creating a Database</h4><p>After installing it, you can create your own database by specifying the name of the database and a table. Imagine that you want to create a database that holds the names of your favorite songs. This scenario would be represented by the following example:</p><pre>import Dexie from &#39;dexie&#39;<br><br>const setupDatabase = () =&gt; {<br>  const database = new Dexie(&#39;MyNewDatabase&#39;)<br>  database.version(1).stores({<br>    songs: &#39;++id&#39;,<br>  })<br>  return database<br>}</pre><p>Each database must have a version, which is 1 in this example. Notice how I called the stores method with an object. In this case, I named the table songs. However, Dexie requires that each song has an ID so that it can easily find it. Therefore, I added the string “++id” to tell Dexie to assign an ID number automatically each time I add something to the database. I have now created my first database! Now I will show you how to add items to it.</p><h4>Adding Items</h4><p>To add a song, you should use the add method on the table that you want to add an item to.</p><pre>const addSong = async () =&gt; {<br>  await database.songs.add({<br>    name: &#39;myNewSong&#39;,<br>  })<br>}</pre><p>Notice how I accessed the table using database.songs and then added the song with a name. It is that simple!</p><h4>Getting Items</h4><p>You can also get songs from the database:</p><pre>const getAllSongs = () =&gt; {<br>  return database.songs.toArray()<br>}</pre><p>The getAllSongs function returns all songs in the database as an array. If you had a song in the database and you called this method, you would get the following output:</p><pre>;[{ name: &#39;myNewSong&#39;, id: 1 }]</pre><h4>Getting a Specific Item</h4><p>You can get a specific song from the database using the get method.</p><pre>const getSong = (id) =&gt; database.songs.get(id)</pre><p>To get a specific song, I need the song’s id. Calling this function with an id of 1 would give you a song like below:</p><pre>{name: &quot;myNewSong&quot;, id: 1}</pre><h4>Updating an Item</h4><p>You can also update a specific item in the database:</p><pre>const updateSong = (id) =&gt;<br>  database.songs.update(id, { name: &#39;My Updated Name&#39; })</pre><p>Calling this function would update the name of a song to be “My Updated Name.”</p><h4>Deleting Items</h4><p>Finally, you can delete a song.</p><pre>const deleteSong = (id) =&gt; database.songs.delete(id)</pre><p>Using these methods, we can manipulate the contents of the database and save the information we need to make requests for the app.</p><h4>Background Sync Implementation</h4><p>To implement background sync, I will use Indexed DB to store the tasks in the main app. This will allow me to get the tasks inside of the service worker and add them whenever a “sync” event fires. First, I will create a database to store the tasks. Second, I will add the tasks to the database and register a tag, indicating that I will create a new task. Third, I will create a sync event listener so that the service worker receives the tag. Fourth, I will use the list of task data inside of the database to create the tasks. Finally, I must delete the tasks from the database so that I do not add duplicates the next time I create a new task. To begin, I will show you how I stored the tasks in the database.</p><p>To store the tasks, I created a new file at src/services/indexedDb.js to set up the database.</p><pre>import Dexie from &#39;dexie&#39;<br><br>const setupDatabase = () =&gt; {<br>  const database = new Dexie(&#39;ProgressiveApp&#39;)<br>  database.version(1).stores({<br>    tasks: &#39;++id&#39;,<br>  })<br>  return database<br>}<br><br>export default setupDatabase</pre><p>Here, I named the database “ProgressiveApp” and created a new table named “tasks.” Notice how I set the id as auto-incrementing. I can now import this file both in my main app and in the service worker to set up the database. Next, I will explain how I stored the tasks.</p><p>Second, I created methods inside of the App.js file to create, get, update, and delete tasks. For this example, I will only add background sync for task creation. Recall that I must first check whether the service worker is available. If the service worker is available, then I must store the tasks in the database and send the sync tag. Take a look at how I created the tasks below. Please note that this is a simplified version of the App component.</p><pre>import setupDatabase from &#39;../services/indexedDb&#39;<br><br>class App extends Component {<br>  // ...other methods<br><br>  database = setupDatabase()<br><br>  // Creates a sync tag called &#39;addTask&#39;<br>  registerBackgroundSync = async () =&gt; {<br>    const registration = await navigator.serviceWorker.ready<br>    await registration.sync.register(&#39;addTask&#39;)<br>  }<br><br>  storeTaskAndSendSignal = async (task) =&gt; {<br>    await this.database.tasks.add(task)<br>    await this.registerBackgroundSync()<br>  }<br><br>  requestAddTask = (task) =&gt; tasksApi.post(&#39;/&#39;, task)<br><br>  // Checks if service worker is available because not all browsers have it.<br>  useBackgroundSyncOrRequest = (task) =&gt; {<br>    const serviceWorkerExists = navigator.serviceWorker<br>    // Creates task with background sync only if the browser supports service workers.<br>    if (serviceWorkerExists) {<br>      return this.storeTaskAndSendSignal(task)<br>    }<br>    // Creates task without background sync.<br>    return this.requestAddTask(task)<br>  }<br><br>  create = async (task) =&gt; {<br>    await this.useBackgroundSyncOrRequest(task)<br>  }<br>}</pre><p>First, I set up the database so that I could access it from the App class using this.database. This allows me to use Dexie’s methods to add, create, get, update, or delete items. Inside of the create method, I called the method useBackgroundSyncOrRequest, which is responsible for verifying whether the service worker is available. When the service worker is available, it adds the task data to the “tasks” table and sends a tag with the name of “addTask.” Otherwise, it will make a network request to the API and create the task instantly, without using background synchronization. This allows both browsers that support background sync and those that do not support it to use the app.</p><p>Next, I need to pass the create method down to the AddTask component, since this component displays the form for creating the task. Although I could pass down the methods manually using props, I will use the React context instead. React context allows you to easily pass data through multiple child components by passing it as a property to a <strong>provider</strong> and having child component access the data with a <strong>consumer</strong>. Think of the provider as a restaurant, while a consumer as one of its customers. Just as the restaurant serves food to the customer, the provider gives data to the consumer. You can read more about it in the article in the resources section below. The following example shows I created the provider.</p><pre>// TasksContext.js<br><br>import React from &#39;react&#39;<br><br>const TasksContext = React.createContext(null)<br><br>export default TasksContext</pre><p>I created a context in the TasksContext.js file so that I can import it in both the App and AddTask components. Next, I will use the Provider property of the TasksContext to pass down the data.</p><pre>// App.js<br><br>class App extends Component {<br>  // ...other methods<br><br>  // Group task methods together.<br>  getProviderValue = () =&gt; ({<br>    tasks: this.state.tasks,<br>    create: this.create,<br>    update: this.update,<br>    delete: this.delete,<br>  })<br><br>  render() {<br>    return (<br>      // Allows child components to access methods.<br>      &lt;TasksContext.Provider value={this.getProviderValue()}&gt;<br>        &lt;Layout&gt;<br>          &lt;h1&gt;Tasks&lt;/h1&gt;<br>          &lt;AddTask /&gt;<br>          &lt;Tasks /&gt;<br>        &lt;/Layout&gt;<br>      &lt;/TasksContext.Provider&gt;<br>    )<br>  }<br>}</pre><p>First, I created an object with the list of tasks with the create, update, and delete methods. By passing them down to the TasksContext.Provider component as the value property, I can allow other child components to use them.</p><p>Then, I used these methods inside of the AddTask component to add a task with a name whenever the form is submitted. Please look at the code below.</p><pre>// AddTask/index.js<br><br>export class AddTask extends Component {<br>  // ...other methods<br><br>  // Allows me to access the data from the provider using this.context.<br>  static contextType = TasksContext<br><br>  addTask = async () =&gt; {<br>    const task = {<br>      title: this.state.title,<br>      isCompleted: false,<br>    }<br>    await this.context.create(task)<br>  }<br><br>  render() {<br>    const id = &#39;add-task&#39;<br>    const formId = `${id}__form`<br>    return (<br>      &lt;TaskModal id={id} formId={formId}&gt;<br>        &lt;form onSubmit={this.onSubmit} id={formId}&gt;<br>          &lt;Name setName={this.setTitle} /&gt;<br>        &lt;/form&gt;<br>      &lt;/TaskModal&gt;<br>    )<br>  }<br>}</pre><p>In this component, I create the task and add it to Indexed DB. Notice how I set the contextType to the TasksContext, which causes the provider to pass the data (the object with the create, update, and delete methods) to the AddTask component. I can access this data using this.context. In the addTask method, I called this.context.add to create a new task inside of Indexed DB. By adding the task inside of the database, I can store the tasks that I want to synchronize inside of Indexed DB and access them in my service worker. Next, I will show you how I modified the service worker.</p><p>To synchronize the data, I must first create an event listener. Recall that a sync event listener fires whenever the network is available, meaning that I should add the tasks whenever the “sync” event fires. The following code shows how I created the event listener:</p><pre>self.addEventListener(&#39;sync&#39;, async (event) =&gt; {<br>  const { tag } = event<br>  if (tag === &#39;addTask&#39;) {<br>    const handler = new AddTaskHandler()<br>    await handler.addTasksAndRemoveOld()<br>  }<br>})</pre><p>Here, I created an event listener for the “sync” event. Recall that this event only fires when the application is back online and that it receives the tag’s name. If the tag’s name is “addTask,” then I should add tasks. To add tasks, I created a new handler called AddTaskHandler. Recall that the service worker must get the list of tasks, make requests for those tasks, and delete them so that it does not add duplicate tasks. Take a look at the handler below, but start reading from the addTasksAndRemoveOld method.</p><pre>class AddTaskHandler {<br>  constructor() {<br>    this.database = setupDatabase()<br>  }<br><br>  getTasksToAdd() {<br>    return this.database.tasks.toArray()<br>  }<br><br>  getTaskData({ title, isCompleted }) {<br>    const task = { title, isCompleted }<br>    return JSON.stringify(task)<br>  }<br><br>  addTask(baseTask) {<br>    const stringifiedData = this.getTaskData(baseTask)<br>    const config = {<br>      method: &#39;POST&#39;,<br>      body: stringifiedData,<br>      headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    }<br>    return fetch(&#39;/api/tasks&#39;, config)<br>  }<br><br>  async addAllTasks(tasks) {<br>    const promises = tasks.map(this.addTask.bind(this))<br>    await Promise.all(promises)<br>  }<br><br>  getTaskIds(tasks) {<br>    return tasks.map(({ id }) =&gt; id)<br>  }<br><br>  async deleteTasks(tasks) {<br>    const ids = this.getTaskIds(tasks)<br>    await this.database.tasks.bulkDelete(ids)<br>  }<br><br>  async addTasksAndRemoveOld() {<br>    const tasks = await this.getTasksToAdd()<br>    await this.addAllTasks(tasks)<br>    await this.deleteTasks(tasks)<br>  }<br>}</pre><p>First, the getTasksToAdd function gets the list of tasks, gets their IDs, and calls the addTask method for each one. After making a network request for each task, I no longer need the tasks in Indexed DB. Since the database should only hold the tasks that the app needs to add, I called the deleteTask function with the task IDs to delete all tasks that were in the database. This way, the app can add tasks whenever the app is back online.</p><p>To test the app, start your server by running npm start and go to <a href="http://localhost:3000/">http://localhost:3000</a>. You should update the service worker by either reloading or closing all of the app’s tabs and opening them again. Since we want to test whether the app works without having access to the API, turn off your server by typing ^C into your terminal. Click on the “Add Task” button in the navigation bar and enter a task name. Then, click enter to submit the form. Although this will not add a task because your server is offline, the task should be stored in Indexed DB. Next, restart your server by running npm start. The app should now detect that you are online and try to make the request. Once the page reloads, you should see your new task in the list of tasks. Congrats! You have added background sync into the app!</p><p>This may seem like a lot of work, but Workbox has a tool that helps developers add background synchronization more efficiently: the workbox-background-sync package. In the following section, I will show you how to use Workbox to add background sync.</p><h4>Adding Background Sync Using Workbox</h4><p>Using Workbox, we can add background synchronization much more easily. To use it, we need to follow a simple process:</p><ol><li>Register a route that Workbox should use background sync for.</li><li>Make a request for adding a task from the app.</li><li>Register a sync tag.</li></ol><p>Once we make a request to the API, Workbox will detect whether the request fails. If it fails, then it will use background synchronization to postpone the request until the application is back online. Next, I will show you how to install the Workbox Background Sync package.</p><p>To install the package, run the following command in your terminal:</p><pre>npm install workbox-background-sync</pre><p>First, we must make a request to the API to create a new task. The following code shows how I created a task from the App component:</p><pre>// src/App.js<br>class App {<br>  // ...other methods<br><br>  registerBackgroundSync = async () =&gt; {<br>    const registration = await navigator.serviceWorker.ready<br>    await registration.sync.register(&#39;addTask&#39;)<br>  }<br><br>  storeTaskAndSendSignal = async (task) =&gt; {<br>    await tasksApi.post(&#39;/&#39;, task)<br>    await this.registerBackgroundSync()<br>  }<br><br>  requestAddTask = (task) =&gt; tasksApi.post(&#39;/&#39;, task)<br><br>  useBackgroundSyncOrRequest = (task) =&gt; {<br>    const serviceWorkerExists = navigator.serviceWorker<br>    if (serviceWorkerExists) {<br>      return this.storeTaskAndSendSignal(task)<br>    }<br>    return this.requestAddTask(task)<br>  }<br><br>  create = async (task) =&gt; {<br>    await this.useBackgroundSyncOrRequest(task)<br>  }<br>}</pre><p>Notice how instead of adding the task to Indexed DB, I called tasksApi.post to add a task using a network request to the API. I still registered a tag named “addTask,” since this is what Workbox will use to identify that it should add a task. I have finished modifying the App component. Next, I will show you how I changed the service worker to use Workbox.</p><p>To use background sync with Workbox, I must first import the workbox-background-sync package. Recall that Workbox uses strategies to respond to requests, some of which include StaleWhileRevalidate and NetworkOnly. Each strategy can accept <strong>plugins</strong>, which add more features. This Workbox Background Sync package contains the BackgroundSyncPlugin, which can be used with the NetworkOnly strategy to add background synchronization. The following code shows you how I accomplished this:</p><pre>import { registerRoute } from &#39;workbox-routing&#39;<br>import { StaleWhileRevalidate, NetworkOnly } from &#39;workbox-strategies&#39;<br>import { BackgroundSyncPlugin } from &#39;workbox-background-sync&#39;<br><br>const backgroundSync = new BackgroundSyncPlugin(&#39;addTask&#39;)<br><br>registerRoute(<br>  new RegExp(&#39;/api/tasks&#39;),<br>  new NetworkOnly({ plugins: [backgroundSync] }),<br>  &#39;POST&#39;<br>)</pre><p>First, I configured the plugin by creating a new instance of it with new BackgroundSyncPlugin(&#39;addTask&#39;). “addTask” is the tag that Workbox uses to identify what is being synchronized, so it must be the same tag that is registered inside of the App component. Then, I registered a route for “/api/tasks” using the NetworkOnly strategy, which means that it always requests data from the network instead of the cache. Inside of the strategy, I added an object with the plugins property, which includes the configured backgroundSync plugin. Finally, notice how I specified “POST” as the third argument in the registerRoute function. By default, Workbox’s strategies only work for “GET” requests, so I had to specify that it should work for POST requests. Next, we will test the app.</p><p>To test the app, you should repeat the same process as before. First, enable your server by running npm start. Second, go to the app on <a href="http://localhost:3000/">http://localhost:3000</a>. Third, turn off your server so that the POST request to the api will fail. Then, try and create a new task. After the request fails, Workbox should store the task. Fifth, turn on your server again. Workbox will not instantly detect that you are back online because it only checks the network status every few minutes. To make the service worker create the tasks immediately, you should manually register a tag. Open the Chrome Development Tools and go to the “Application” tab. Then, click on the “Service Workers” section in the sidebar. You should see an input field labeled “sync” on the right side.</p><figure><img alt="The Chrome Developer Tools with a field labeled &quot;Sync&quot; on the right side. It has the tag &quot;workbox-background-sync:addTask.&quot;" src="https://cdn-images-1.medium.com/max/1024/0*yP19t35PC7oBAGil.png" /></figure><p>In the input field, type workbox-background-sync:addTask. Notice how this is the tag we registered prepended with “workbox-background-sync.” Finally, click the “Sync” button. The tasks should now be created. Reload the page to see the newly created tasks. Congratulations! You have added background synchronization using Workbox!</p><h4>Conclusion</h4><p>In this article, you learned that background synchronization postpones requests until the app is online. Background synchronization works even when the application and browser are closed, but not all browsers support it. You learned the basic concept behind background sync and learned to use Dexie with Indexed DB to store data in a database. Then, you learned how to make an event listener in the service worker, get items from the database, and make requests for them. Finally, you learned that Workbox provides a much more efficient solution for adding background synchronization with the workbox-background-sync package. By registering a route and using the plugin, you can automatically postpone requests until the network is available. Thank you for reading this article! If you have any questions, please feel free to ask them in the comments below! In the next article, I will show you how to prepare your application for production.</p><h3>Resources</h3><p><a href="https://reactjs.org/docs/context.html">Context — React</a></p><p><a href="https://developers.google.com/web/tools/workbox/modules/workbox-background-sync">Workbox Background Sync</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5028080d611e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/super-coder/background-synchronization-5028080d611e">Background Synchronization</a> was originally published in <a href="https://medium.com/super-coder">Super-coder</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>