> Markdown version of [Work Offline](https://vaadin.com/docs/next/building-apps/react/work-offline). Section index: [llms.txt](https://vaadin.com/docs/next/building-apps/llms.txt)

# Work Offline

A React view runs in the browser, so it can keep working when the browser can’t reach the server. This guide shows how to make the application load without the server, and how to keep the data of a view available. Flow views need the server, so they show an offline page instead.

The guide covers reading data offline. A call that changes data fails while the server can’t be reached. To let users make changes offline, the application has to store them in the browser and send them when the connection is back.

## <a id="caching-the-application"></a>Caching the Application

Add the `@PWA` annotation to the application shell class. Vaadin then generates a service worker, which caches the application shell and the frontend files, including the React views:

```java
@PWA(name = "Task Tracker", shortName = "Tasks")
public class Application implements AppShellConfigurator {
    // ...
}
```

The browser installs the service worker the first time it opens the application. After that, the application loads from the cache when the server can’t be reached, and React views open as usual. Try this with a production build: in development mode, the service worker doesn’t cache the frontend files.

The service worker doesn’t cache the data that views get from services. For the other options of the annotation, see [Progressive Web Applications](https://vaadin.com/docs/next/flow/configuration/pwa.md).

## <a id="keeping-data-in-the-browser"></a>Keeping Data in the Browser

A service call fails when the server can’t be reached. To show data anyway, store the result of each successful call in the browser, and use the stored result when a call fails. The following helper does this with local storage:

`cacheable.ts`

`cacheable.ts`

```typescript
import { EndpointError } from '@vaadin/hilla-frontend';

const CACHE_KEY = 'offline-cache';

function readCache(): Record<string, unknown> {
  return JSON.parse(localStorage.getItem(CACHE_KEY) ?? '{}') as Record<string, unknown>;
}

/**
 * Calls a service and stores the result in the browser. When the server
 * can't be reached, returns the stored result, or the default value.
 */
export async function cacheable<T>(
  key: string,
  call: () => Promise<T>,
  defaultValue: T
): Promise<T> {
  try {
    const result = await call();
    localStorage.setItem(CACHE_KEY, JSON.stringify({ ...readCache(), [key]: result }));
    return result;
  } catch (error) {
    if (error instanceof EndpointError) {
      // The server answered with an error, such as access denied
      throw error;
    }
    const cached = readCache()[key];
    return cached === undefined ? defaultValue : (cached as T);
  }
}

export function clearCache(): void {
  localStorage.removeItem(CACHE_KEY);
}
```

The helper uses the stored result only when the call doesn’t reach the server. When the server answers with an error, such as access denied, the call throws an `EndpointError`, which the helper passes on. For more about errors, see [Errors](https://vaadin.com/docs/next/flow/react-views/browser-callable-services.md#errors) in the reference.

Wrap the service calls of a view with the helper:

`views/tasks.tsx`

`tasks-view.tsx`

```tsx
export default function TasksView() {
  const tasks = useSignal<Task[]>([]);

  useEffect(() => {
    cacheable('tasks', TaskService.findTasks, []).then(
      (result) => {
        tasks.value = result;
      },
      (error: unknown) => {
        console.error('Loading the tasks failed', error);
      }
    );
  }, []);

  return (
    <ul>
      {tasks.value.map((task) => (
        <li key={task.title}>{task.title}</li>
      ))}
    </ul>
  );
}
```

When the browser opens the view without a connection to the server, the view shows the tasks that it stored the last time, or an empty list.

## <a id="showing-the-connection-status"></a>Showing the Connection Status

Vaadin shows a status message at the top of the page when a call can’t reach the server. You don’t need to add anything for it. To change its texts or its look, see [Loading and Connection Indicator](https://vaadin.com/docs/next/flow/advanced/loading-indicator.md).

## <a id="clearing-the-data-at-logout"></a>Clearing the Data at Logout

The data in local storage stays in the browser after the user logs out. Whoever uses the browser next can read it. Clear the data that may not stay before you log the user out:

```tsx
import { Button } from '@vaadin/react-components';
import { clearCache } from 'Frontend/cacheable';
import { useAuth } from 'Frontend/security/auth';

export default function LogoutButton() {
  const { logout } = useAuth();
  return (
    <Button
      onClick={async () => {
        clearCache();
        await logout();
      }}
    >
      Logout
    </Button>
  );
}
```

For how to add login and logout, see [Secure React Views](https://vaadin.com/docs/next/building-apps/react/security.md).
