We have a Blazor website made, but the client needs it to work offline.
I need to load all the data necessary when there is internet connection so that i can later use it in the pages. Not just reading the data but also writing new data that would then be synced to the database upon the users request. This solution should work for both mobile and desktop.
Is there a way to make this happen in Blazor? Or would it be easier to use some other tecnology?
I have tried to explore the Blazor WASM PWA, i tried tinkering around with some libraries to use IndexedDb but with little success. Either the library didnt work or there would be a problem getting data.
João Rodrigues is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5
I tried with Tavenem.Blazor.IndexedDB
and it works when offline.You could try following steps.
Create a .net8 wasm-standalone pwa project. Modify the “service-worker.js” like below: (I just cache resource when visit 1st time)
const cacheName = `myCache`;
const assetsToCache = [
'/favicon.png'
];
self.addEventListener('install', event => {
console.log('V1 installing…');
event.waitUntil(
caches.open(cacheName).then(cache => cache.addAll(assetsToCache))
);
});
self.addEventListener('activate', event => {
console.log('Cache now ready to handle fetches!');
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if (cachedResponse) {
// Return the cached response if found
return cachedResponse;
}
// If the request is not in the cache, fetch from the network
return fetch(event.request).then(networkResponse => {
// Open the cache and store the network response
const responseToCache = networkResponse.clone();
caches.open(cacheName).then(cache => {
cache.put(event.request, responseToCache);
});
return networkResponse;
});
})
);
});
Install Tavenem.Blazor.IndexedDB
program.cs
builder.Services.AddIndexedDbService();
Home.razor
@page "/"
@using Tavenem.Blazor.IndexedDB
@using Tavenem.DataStorage
@inject IndexedDbService _indexedDbService
abc
<button @onclick="test">test</button>
@code{
private async Task test(){
var item = new Item
{
Id = "1",
Value = "Hello, World!",
};
var db = new IndexedDb("myDatabaseName",_indexedDbService,1);
await db["store1"].StoreItemAsync<Item>(item);
}
public class Item : IdItem
{
public string? Value { get; set; }
}
}
Reference: https://github.com/Tavenem/Blazor.IndexedDB
3