S
S
Sergey2021-06-23 12:46:42
caching
Sergey, 2021-06-23 12:46:42

Is it possible to save multiple images offline via PWA for later sharing?

There is a React + PWA application that allows you to send a lot of photos. Approximately - up to 50. Accordingly, when there is a network, then there are no problems.
And when there is no network, can you somehow save / cache all the photos so that when the Internet appears, they themselves fly to the server?
Are there any restrictions on this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2021-06-23
@Aleksandr-JS-Developer

I have not come across such cases, but the first thing that comes to mind is to get pictures and write them, say, to IndexedDB. Then take it from there. A lot can fit into IndexedDB. Some browsers have limitations, but in general, 50 images will definitely fit.
Links:
IndexedDB API (MDN)
IndexedDB API (learn.javascript)
https://caniuse.com/indexeddb (93.62% + 4.29% = 97.91% )

A
Alexey Yarkov, 2021-06-23
@yarkov

At work, for a service worker in PWA, we use a workbox.
We do not send pictures, but there are many different forms. And just a similar case.

import { NetworkOnly } from 'workbox-strategies';
import { BackgroundSyncPlugin } from 'workbox-background-sync';
import { registerRoute } from 'workbox-routing';
import { StatusCodes } from 'http-status-codes';

const bgSyncPlugin = new BackgroundSyncPlugin('APIRequestsQueue', {
  // Повторять попытку отправить запрос в течение 8 часов (указывается в минутах)
  maxRetentionTime: 480,
});

['POST', 'PUT', 'PATCH', 'DELETE'].forEach((method) => {
  registerRoute(
    ({ url }) => url.pathname.startsWith('/v1'),
    new NetworkOnly({
      plugins: [
        {
          ...bgSyncPlugin,
          /**
           * Этот обработчик будет вызван, когда не удалось выполнить запрос.
           * Информация о запросе будет помещена в очередь и запрос
           * выполнится при подключении к сети.
           * Возвращаем статус 202 Accepted, чтобы в приложении
           * можно было понять из-за чего не удалось выполнить запрос
           * и отреагировать должным образом.
          */
          handlerDidError() {
            return Promise.resolve(new Response(null, {
              status: StatusCodes.ACCEPTED,
            }));
          },
        },
      ],
    }),
    method,
  );
});

Thus, the following procedure is achieved:
1. Fill out the form
2. The Internet
disappears 3. Click the SEND button
4. The service worker saves the request data in a cache named APIRequestsQueue and returns 202 code
5. The network appears
6. Requests from the APIRequestsQueue cache go one by one to background, without user interaction

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question