Files
gh-jamshu-jamshi-marketplac…/commands/clear-cache.md
2025-11-29 18:50:06 +08:00

12 KiB

Clear all cached data from your Odoo PWA application.

What this command does:

  • Clears localStorage cache
  • Clears IndexedDB data
  • Clears browser cache
  • Resets service worker cache
  • Forces fresh data fetch from Odoo
  • Provides selective clearing options

When to Use This Command

Good Reasons:

  • Data appears corrupted or inconsistent
  • Testing fresh installation
  • After Odoo schema changes
  • Debugging sync issues
  • After major updates
  • Stuck with old data

⚠️ Caution:

  • Clears all offline data
  • May lose unsyncedchanges
  • Requires re-download of all data
  • User will need to be online

Quick Clear Options

Option 1: Clear from Browser Console (Fastest)

// Clear localStorage
localStorage.clear();

// Clear and refresh
localStorage.clear();
location.reload();

Option 2: Clear from Cache Store

// Using cache store method
expenseCache.clearCache();
expenseCache.refresh();

Option 3: Clear from UI

Add a button to your app:

<button onclick={() => {
  if (confirm('Clear all cached data?')) {
    expenseCache.clearCache();
    expenseCache.refresh();
  }
}}>
  Clear Cache
</button>

Complete Clear Procedure

Step 1: Prepare

□ Save any unsaved work
□ Ensure internet connection
□ Note current state (for comparison)
□ Close other tabs with same app

Step 2: Clear localStorage

// Clear all
localStorage.clear();

// Or clear specific keys
localStorage.removeItem('expenseCache');
localStorage.removeItem('taskCache');
localStorage.removeItem('partnerCache');

Step 3: Clear IndexedDB

// Via DevTools:
// 1. Open DevTools (F12)
// 2. Go to Application tab
// 3. Expand IndexedDB in left sidebar
// 4. Right-click on database → Delete

// Or programmatically:
indexedDB.deleteDatabase('odoo-pwa-db');

Step 4: Clear Service Worker Cache

// Unregister service worker
navigator.serviceWorker.getRegistrations()
  .then(registrations => {
    registrations.forEach(reg => reg.unregister());
  });

// Clear all caches
caches.keys()
  .then(keys => Promise.all(
    keys.map(key => caches.delete(key))
  ));

Step 5: Clear Browser Cache

Chrome/Edge: Ctrl+Shift+Delete → Select cache → Clear
Firefox: Ctrl+Shift+Delete → Select cache → Clear now
Safari: Cmd+Option+E

Step 6: Hard Refresh

Windows/Linux: Ctrl+Shift+R or Ctrl+F5
Mac: Cmd+Shift+R

Step 7: Verify

// Check localStorage is empty
console.log('localStorage size:', localStorage.length);

// Check IndexedDB
// DevTools → Application → IndexedDB
// Should be empty or recreated

// Check cache stores
console.log('Records:', $expenseCache.length);
// Should be 0 or freshly fetched

Selective Clearing

Clear Only Specific Model Cache

// Clear just expense cache
localStorage.removeItem('expenseCache');

// Refresh that cache
expenseCache.refresh();

Clear Only Metadata (Keep Records)

// Get current cache data
const cacheData = JSON.parse(localStorage.getItem('expenseCache'));

// Reset only metadata
cacheData.lastSyncTime = 0;
cacheData.lastRecordId = 0;

// Save back
localStorage.setItem('expenseCache', JSON.stringify(cacheData));

// Force sync
expenseCache.refresh();

Clear Only Old Records

// Keep only recent records (last 30 days)
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

expenseCache.records.update(records =>
  records.filter(r => new Date(r.x_studio_date) > thirtyDaysAgo)
);

Framework-Specific Clearing

SvelteKit

// Clear and reset store
import { expenseCache } from '$lib/stores/expenseCache';

expenseCache.clearCache();
expenseCache.load(); // Reload fresh data

React

// Using Context
import { useExpense } from './contexts/ExpenseContext';

function ClearCacheButton() {
  const { clearCache, refresh } = useExpense();

  return (
    <button onClick={() => {
      clearCache();
      refresh();
    }}>
      Clear Cache
    </button>
  );
}

Vue

// Using Pinia store
import { useExpenseStore } from '@/stores/expenseStore';

const expenseStore = useExpenseStore();

function clearAndRefresh() {
  expenseStore.clearCache();
  expenseStore.load();
}

Advanced Cache Management

Schedule Automatic Cache Clear

// Clear cache older than 7 days
const CACHE_MAX_AGE = 7 * 24 * 60 * 60 * 1000; // 7 days

function checkCacheAge() {
  const cacheData = JSON.parse(localStorage.getItem('expenseCache'));

  if (cacheData && cacheData.lastSyncTime) {
    const age = Date.now() - cacheData.lastSyncTime;

    if (age > CACHE_MAX_AGE) {
      console.log('Cache too old, clearing...');
      expenseCache.clearCache();
      expenseCache.refresh();
    }
  }
}

// Check on app load
checkCacheAge();

Clear on Version Change

// In cache store
const CACHE_VERSION = 2; // Increment when schema changes

function checkCacheVersion() {
  const cacheData = JSON.parse(localStorage.getItem('expenseCache'));

  if (!cacheData || cacheData.version !== CACHE_VERSION) {
    console.log('Cache version mismatch, clearing...');
    clearCache();

    // Set new version
    localStorage.setItem('expenseCache', JSON.stringify({
      version: CACHE_VERSION,
      lastSyncTime: 0,
      lastRecordId: 0
    }));
  }
}

Clear Based on Storage Quota

// Check storage usage
if (navigator.storage && navigator.storage.estimate) {
  navigator.storage.estimate().then(estimate => {
    const percentUsed = (estimate.usage / estimate.quota) * 100;

    console.log(`Storage: ${percentUsed.toFixed(2)}% used`);

    if (percentUsed > 90) {
      console.warn('Storage almost full, clearing old cache...');
      clearOldestRecords();
    }
  });
}

function clearOldestRecords() {
  // Keep only most recent 100 records
  expenseCache.records.update(records =>
    records
      .sort((a, b) => b.id - a.id)
      .slice(0, 100)
  );
}

Cache Verification

After Clearing, Verify:

1. Storage is Empty

console.log('localStorage keys:', Object.keys(localStorage));
// Should be [] or minimal

console.log('localStorage size:', localStorage.length);
// Should be 0 or very small

2. IndexedDB is Clear

DevTools → Application → IndexedDB
- Check if database exists
- Check if tables are empty

3. Fresh Data Loads

// Refresh and watch console
location.reload();

// Should see:
// "Cache miss, fetching from Odoo..."
// "Fetched X records"

4. Functionality Works

□ Data loads correctly
□ CRUD operations work
□ Sync happens
□ Offline mode works after re-caching

Troubleshooting Clear Issues

Issue: Cache Won't Clear

Solution 1: Force with DevTools

1. Open DevTools (F12)
2. Application tab
3. Clear storage section
4. Check all boxes
5. Click "Clear site data"

Solution 2: Use Private/Incognito

Open app in private browsing mode
- Fresh session, no cache
- Test functionality

Solution 3: Different Browser

Test in different browser
- Rules out browser-specific issues

Issue: Data Reappears After Clear

Solution: Check Multiple Sources

// Clear all possible locations
localStorage.clear();
sessionStorage.clear();
indexedDB.deleteDatabase('odoo-pwa-db');

// Unregister service workers
navigator.serviceWorker.getRegistrations()
  .then(regs => regs.forEach(reg => reg.unregister()));

// Clear all caches
caches.keys()
  .then(keys => Promise.all(keys.map(k => caches.delete(k))));

Issue: App Breaks After Clear

Solution: Ensure Graceful Degradation

// In cache store, handle missing cache
function loadFromCache() {
  try {
    const cached = localStorage.getItem('expenseCache');

    if (!cached) {
      console.log('No cache, will fetch from Odoo');
      return { records: [], lastRecordId: 0, lastSyncTime: 0 };
    }

    return JSON.parse(cached);
  } catch (error) {
    console.error('Error loading cache:', error);
    return { records: [], lastRecordId: 0, lastSyncTime: 0 };
  }
}

User-Facing Clear Options

Settings Page Example

<script>
  import { expenseCache, taskCache } from '$lib/stores';

  async function clearAll() {
    if (confirm('Clear all cached data? This cannot be undone.')) {
      expenseCache.clearCache();
      taskCache.clearCache();

      alert('Cache cleared! Refreshing...');
      location.reload();
    }
  }

  async function clearExpenses() {
    if (confirm('Clear expense cache?')) {
      expenseCache.clearCache();
      await expenseCache.refresh();
      alert('Expense cache cleared!');
    }
  }

  function getCacheInfo() {
    const size = new Blob(Object.values(localStorage)).size;
    const sizeKB = (size / 1024).toFixed(2);
    return { count: localStorage.length, sizeKB };
  }
</script>

<div class="settings">
  <h2>Cache Management</h2>

  <div class="cache-info">
    <p>Items: {getCacheInfo().count}</p>
    <p>Size: {getCacheInfo().sizeKB} KB</p>
    <p>Last sync: {new Date($expenseCache.lastSync).toLocaleString()}</p>
  </div>

  <div class="actions">
    <button on:click={clearExpenses}>Clear Expense Cache</button>
    <button on:click={clearAll} class="danger">Clear All Cache</button>
  </div>
</div>

<style>
  .danger {
    background: red;
    color: white;
  }
</style>

Cache Clear Checklist

Before clearing:

□ Save any unsaved work
□ Note current state
□ Ensure internet connection
□ Close duplicate tabs

After clearing:

□ localStorage is empty
□ IndexedDB is cleared
□ Service worker cache cleared
□ Fresh data loaded
□ Functionality tested
□ Sync works correctly
□ Offline mode re-enabled (after cache rebuilt)

Best Practices

1. Clear Strategically

  • Don't clear unnecessarily
  • Clear only what's needed
  • Keep user data when possible

2. Warn Users

function clearCache() {
  const message = `
    This will clear all cached data.
    You'll need to re-download everything from Odoo.
    Continue?
  `;

  if (confirm(message)) {
    // Proceed
  }
}

3. Provide Progress

async function clearAndRefresh() {
  alert('Clearing cache...');

  localStorage.clear();

  alert('Fetching fresh data...');

  await expenseCache.refresh();

  alert('Done! Cache rebuilt.');
}

4. Log for Debugging

function clearCache() {
  console.log('Before clear:', {
    localStorage: localStorage.length,
    records: $expenseCache.length
  });

  localStorage.clear();
  expenseCache.clearCache();

  console.log('After clear:', {
    localStorage: localStorage.length,
    records: $expenseCache.length
  });
}

5. Test Regularly

  • Test cache clear functionality
  • Ensure app works after clear
  • Verify data re-downloads
  • Check offline mode recovers

Example prompts to use this command:

  • /clear-cache - Clear all cached data
  • User: "Clear my cache"
  • User: "Data looks wrong, clear everything"
  • User: "Reset the app"
  • /fix-sync - If sync issues persist
  • /test-connection - Test after clearing
  • /troubleshoot - For other issues
  • /help - Full documentation

Quick Reference

Clear Everything (Nuclear Option)

// Copy-paste into console
localStorage.clear();
sessionStorage.clear();
indexedDB.databases().then(dbs =>
  dbs.forEach(db => indexedDB.deleteDatabase(db.name))
);
navigator.serviceWorker.getRegistrations().then(regs =>
  regs.forEach(reg => reg.unregister())
);
caches.keys().then(keys =>
  keys.forEach(key => caches.delete(key))
);
location.reload(true);

Clear Specific Model

localStorage.removeItem('expenseCache');
expenseCache.refresh();

Reset Metadata Only

const cache = JSON.parse(localStorage.getItem('expenseCache'));
cache.lastSyncTime = 0;
cache.lastRecordId = 0;
localStorage.setItem('expenseCache', JSON.stringify(cache));
expenseCache.refresh();