# Sync Mode (AutoSync vs Batch)

## Content

Remote tables support two synchronization modes:

* **Single Sync Mode**
* **Batch Sync Mode**

Synchronization mode determines:

* When changes are sent to the server
* How requests are structured
* Whether changes are transactional

The mode is configured when creating the table.

## Single Sync Mode (autoSync)

In single sync mode, each data change triggers an immediate remote request.
Enable it by setting:

```javascript
autoSync: true
```

Example:

```javascript
const dataManager = spread.dataManager();

const orders = dataManager.addTable("orders", {
    remote: {
        read:   { url: "http://localhost:3000/api/orders", method: "GET" },
        create: { url: "http://localhost:3000/api/orders", method: "POST" },
        update: { url: "http://localhost:3000/api/orders", method: "PUT" },
        delete: { url: "http://localhost:3000/api/orders", method: "DELETE" }
    },
    autoSync: true
});

orders.fetch();
```

Behavior:

* Insert → sends `create`
* Update → sends `update`
* Delete → sends `delete`
* Each operation sends a separate request
* No manual submission required

Use single sync mode when:

* Immediate persistence is required
* Each operation is independent
* Simplicity is preferred over batching

## Batch Sync Mode

In batch mode, changes are stored locally until explicitly submitted.
Enable it by setting:

```javascript
batch: true
```

Example:

```javascript
const orders = dataManager.addTable("orders", {
    remote: {
        read:  { url: "http://localhost:3000/api/orders", method: "GET" },
        batch: { url: "http://localhost:3000/api/orders/batch", method: "POST" }
    },
    batch: true
});

orders.fetch();
```

Behavior:

* Insert/update/delete operations are cached locally
* No immediate network request is sent
* All changes are submitted together

To send changes:

```javascript
orders.submitChanges();
```

To discard changes:

```javascript
orders.cancelChanges();
```

## Behavior Comparison

| Feature | Single Sync | Batch Sync |
| ------- | ----------- | ---------- |
| Network calls | Per operation | One request |
| Manual submission | Not required | Required |
| Transaction-like behavior | No | Yes |
| Failure handling | Per operation | Entire batch |

Batch mode is appropriate when:

* Multiple changes must succeed or fail together
* Network traffic should be minimized
* Server-side transaction handling is implemented

## Change Lifecycle

In single sync mode:

1. User modifies data
2. Remote request is sent immediately
3. Server response updates table state

In batch mode:

1. User modifies data
2. Change is stored locally
3. `submitChanges()` sends all changes
4. Server returns aggregated result
5. Table state is finalized

## Important Notes

* `read` must always be defined.
* Single sync mode requires `create`, `update`, and `delete`.
* Batch mode requires `batch`.
* Only one mode should be enabled.
* All tables must call `fetch()` before editing.