# useContent()

To streamline data management within your application, you can utilize the powerful capabilities offered by `useContent`, a feature provided by the `@magicjs.dev/frontend` library.

Here's a concise example of how to integrate `useContent` into your application:

```javascript
import { createComponent, Frontend } from '@magicjs.dev/frontend';

export default createComponent((props) => {
  // Destructure the useContent function from the provided props
  const { useContent } = props.use(Frontend);

  // Initialize contentEditor using useContent
  const contentEditor = useContent({
    serviceId: "uniqueIdentifier", // Ensure serviceId is unique
    defaultContent: {/* Add your default content here */},
    useReduxStore: false, // Control whether to utilize Redux store for data management
  });
})
```

Here are some key points to consider:

* **Unique Service ID**: It's crucial to assign a unique `serviceId` to each instance of `useContent`. This identifier distinguishes between different data services and ensures proper management and isolation of data.
* **Default Content**: If you wish to provide default content upon initialization, you can do so by setting the `defaultContent` parameter. This allows for seamless rendering of content without the need for additional checks or handling.
* **Redux Store Integration**: By toggling the `useReduxStore` parameter, you can control whether changes to data propagate across components. Setting it to `true` enables synchronization of data changes, facilitating consistent state management throughout your application.

## Operations

* [setContent](#setcontent)
* [updateKey](#updatekey)
* [pushItem](#pushitem)
* [removeItemAt](#removeitemat)
* [runBatch](#runbatch)
* [hasChanged](#haschanged)
* [markAsSaved](#markassaved)
* [saveLocally](#savelocally)
* [getPendingLogs](#getpendinglogs)
* [resetPendingLogs](#resetpendinglogs)
* [insertItem](#insertitem)
* [unshiftItem](#unshiftitem)
* [reset](#reset)

### setContent

> **Type:** Function

The `setContent()` function is used to update the content with new information. It accepts an object with various properties as its argument. For example, it could be used to update the contents of a text editor or content management system.

> Example:

```tsx
<button
  onClick={contentEditor.setContent({
    title: 'Sample',
    keyA: 1,
    keyB: 2,
    items: [1, 2, 3],
    emptyArrayToPush: [],
    itemsToRemoveFrom: ['a', 'b', 'c', 'd', 'e'],
    innerObj: {
      collection: [
        {
          subTitle: 'Collection Sub Title',
        },
      ],
    },
  })}
>
  Set Content
</button>
```

You can use `console.log(contentEditor.content)` to see the data contained by the `content` property of `contentEditor`.

### updateKey

**Type:** Function

The `updateKey()` function is used to update a property in an object. It accepts two arguments:

<table data-full-width="false"><thead><tr><th>Name</th><th>Type</th><th>Description</th><th>Required</th><th>Default</th></tr></thead><tbody><tr><td>key</td><td>string</td><td>The name of the property to update.</td><td>Yes</td><td></td></tr><tr><td>value</td><td>any</td><td>The new value to assign to the property.</td><td>Yes</td><td></td></tr></tbody></table>

> Example:

```tsx
<button
  onClick={() => {
    updateKey('title', 'Sample Updated Title');
  }}
>
  Update Title
</button>
```

### pushItem

**Type:** Function

The `pushItem()` function is used to push data to an array. It accepts two arguments:

| Name  | Type   | Description                       | Required | Default |
| ----- | ------ | --------------------------------- | -------- | ------- |
| key   | string | The name of the array to push to. | Yes      |         |
| value | any    | The value to push to the array.   | Yes      |         |

> Example:

**Push a value to an array:**

```tsx
<button 
  onClick={() => {
      pushItem('items', 4);
  }}
>
  Push to Items Array
</button>
```

In the code above, `pushItem` is a function that takes two arguments: the name of the array and the value you want to push to that array. In this case, we are pushing the number `4` to the `items` array. When the button is clicked, the `onClick` event executes the `pushItem` function, which updates the `items` array by adding `4` to the end of it.

### removeItemAt

**Type:** Function

The `removeItemAt()` function is used to remove an item from an array at a specific index. It accepts two arguments:

| Name  | Type   | Description                                     | Required | Default |
| ----- | ------ | ----------------------------------------------- | -------- | ------- |
| key   | string | The name of the array to remove the item from.  | Yes      |         |
| value | number | The index of the item to remove from the array. | Yes      |         |

> Example:

**Remove an item at a specific index:**

```tsx
<button
  onClick={() => {
    contentEditor.removeItemAt('itemsToRemoveFrom', 5);
  }}
>
  Remove item at index 5
</button>
```

In the code above, you can replace `itemsToRemoveFrom` with the variable that you want to remove an item from, and `5` with the index of the item that you want to remove.

### runBatch

**Type:** Function

The `runBatch()` function is used to perform multiple operations (remove, update, and push) in a single operation. It accepts an object with various properties as its argument.

> Example:

**Button that updates multiple keys at once**

```tsx
<button onClick={() => {
  runBatch(() => {
    updateKey('keyA', 100);
    updateKey('keyB', 200);
  });
}}>
  Update multiple key
</button>
```

Here, two functions named `runBatch` and `updateKey` to update the values of two keys ('keyA' and 'keyB') in the object.

**Button that push multiple items to an array at once**

```tsx
 <button
  onClick={() => {
    runBatch(() => {
      pushItem('emptyArrayToPush', 100);
      pushItem('emptyArrayToPush', 200);
    });
  }}
>
  Push multiple items
</button>
```

Here, two functions named `runBatch` and `pushItem` to push two items (100 and 200) to an array named `emptyArrayToPush`.

**Remove Items at specific indices from an array at once**

```tsx
<button
  onClick={() => {
    runBatch(() => {
      removeItemAt('itemsToRemoveFrom', 3);
      removeItemAt('itemsToRemoveFrom', 5);
    });
  }}
>
  Remove items at indices 3 and 5
</button>
```

Here, two functions named `runBatch` and `removeItemAt` to remove items from an array named `itemsToRemoveFrom`. In this case, items at index 3 and index 5 will be removed.

* The `runBatch` function accepts a function as an argument and runs it as a batch operation, which can help improve performance when updating multiple operations at once.

{% hint style="info" %}
It is not recommended to use asynchronous code inside `runBatch` function as it may cause unexpected behavior.
{% endhint %}

### hasChanged

**Type:** Boolean

The `hasChanged` is a boolean that indicates whether any changes have been made to the content.

### markAsSaved

**Type:** Function

The `markAsSaved()` is used to mark the content as saved.

### saveLocally

**Type:** Function

The `saveLocally()` is used to save the content in local storage.

### getPendingLogs

**Type:** Function

The `getPendingLogs()` is used to retrieve the pending action logs.

### resetPendingLogs

**Type:** Function

The `resetPendingLogs()` is used to reset the pending action logs.

### insertItem

**Type:** Function

The `insertItem()` is used to insert an item into a specified key at the given index.

### **unshiftItem**

**Type:** Function

The `unshiftItem()` facilitates moving an item to the initial position within a collection.

### **reset**

**Type:** Function

The `reset()` is used to reset content to its initial state.

> [Click here to refer GitHub.](https://github.com/skyslit/magicjs.dev/blob/main/packages/frontend/src/content.ts)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://skyslit.gitbook.io/magicjs/api-references/frontend/usecontent.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
