> For the complete documentation index, see [llms.txt](https://skyslit.gitbook.io/magicjs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://skyslit.gitbook.io/magicjs/basic-guide/advanced-state-management-with-usecontent.md).

# Advanced State Management with useContent()

{% embed url="<https://www.youtube.com/watch?v=xD3vII_AWmU>" %}
Advanced State management with useContent()
{% endembed %}

## Setting Up

1. Begin by creating a file named `form` and assigning the path `/form` in the main-features folder.
2. Import `useContent` from `@magicjs.dev/frontend`.
3. Initialize a state using the `useContent()` hook.

```tsx
const cms = useContent();
```

3. Render the content using a code tag, allowing for easy visualization of the state's structure.

> Refer the snippet below.

```tsx
<code>
    {JSON.stringify(cms.content, undefined, ' ')}
</code>
```

## Setting Content

Implement a button labelled "Set Content" to initiate the setting of complex objects within the state.&#x20;

> Refer the snippet below.

```tsx
<Button
    onClick={() =>
        cms.setContent({
            title: "My Blog",
            body: "About My Blog",
            recipes: [
                {
                    id: 1,
                    itemName: "Milk",
                    qty: 3,
                },
            ],
        })
    }
>
    Set Content
</Button>
```

Upon clicking, the state is updated with predetermined content.

## Updating Content

To facilitate dynamic updates, integrate a button labelled "Update body" that enables the modification of the body content. Upon clicking, the body content is updated.

> Refer the snippet below.

```tsx
<Button onClick={() => cms.updateKey("body", "My updated body")}>
    Update Body
</Button>
```

## Adding Items

Enhance the form's functionality by incorporating a button titled "Add Recipe" to dynamically append additional recipes. Upon activation, a new recipe is seamlessly integrated into the existing state.

> Refer the snippet below.

```tsx
<Button
    onClick={() => cms.pushItem("recipes", { id: 2, itemName: "Sugar" })}
>
    Add Recipe
</Button>
```

## Updating Items

For precise control over individual items, introduce a button labelled "Update milk qty to 4" to adjust the quantity of specific items. Through targeted updates, we can fine-tune the state to reflect real-time changes.

> Refer the snippet below.

```tsx
<Button onClick={() => cms.updateKey("recipes.[1].qty", 4)}>
    Update Milk Qty to 4
</Button>
```

Through the exploration of MagicJS's `useContent()` hook, developers gain access to advanced state management capabilities, empowering them to create dynamic and responsive forms effortlessly.

> Final Code and Output is given below for reference.

```tsx
import { useContent } from "@magicjs.dev/frontend"
import { Button } from "antd"
import React from "react"

export default function Component(props: any) {
    const cms = useContent()

    return (
        <div>
            <Button
                onClick={() =>
                    cms.setContent({
                        title: "My Blog",
                        body: "About My Blog",
                        recipes: [
                            {
                                id: 1,
                                itemName: "Milk",
                                qty: 3,
                            }
                        ]
                    })}>
                Set Content
            </Button>

            <Button onClick={() => cms.updateKey("body", "My updated body")}>
                Update Body
            </Button>

            <Button
                onClick={() => cms.pushItem("recipes", { id: 2, itemName: "Sugar" })}
            >
                Add Recipe
            </Button>

            <Button onClick={() => cms.updateKey("recipes.[1].qty", 4)}>
                Update Milk Qty to 4
            </Button>

            <code>{JSON.stringify(cms.content, undefined, " ")}</code>
        </div>
    )
}
```

<details>

<summary>Expand for Tailwind styled code.</summary>

{% code lineNumbers="true" %}

```typescript
import { useContent } from "@magicjs.dev/frontend"
import { Button } from "antd"
import React from "react"

export default function Component(props: any) {
  const cms = useContent()

  return (
    <div className="h-screen flex items-center justify-center">
      <div className="flex flex-col items-center">
        <div className="mb-4">
          <Button
            onClick={() =>
              cms.setContent({
                title: "My Blog",
                body: "About My Blog",
                recipes: [
                  {
                    id: 1,
                    itemName: "Milk",
                    qty: 3,
                  }
                ]
              })}
            className="text-xl w-40 h-14">
            Set Content
          </Button>

          <Button
            onClick={() => cms.updateKey("body", "My updated body")}
            className="text-xl w-40 h-14">
            Update Body
          </Button>

          <Button
            onClick={() => cms.pushItem("recipes", { id: 2, itemName: "Sugar" })}
            className="text-xl w-40 h-14">
            Add Recipe
          </Button>

          <Button
            onClick={() => cms.updateKey("recipes.[1].qty", 4)}
            className="text-xl w-56 h-14">
            Update Milk Qty to 4
          </Button>
        </div>

        <div> {/* Container for code */}
          <code>{JSON.stringify(cms.content, undefined, " ")}</code>
        </div>
      </div>
    </div>
  )
}
```

{% endcode %}

</details>

<figure><img src="/files/6HbiNJgvVsZ8ZLc7GNXd" alt=""><figcaption><p>Output</p></figcaption></figure>

:tada: Congratulations! You've learned Advanced State Management using `useContent()` in MagicJS framework.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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/basic-guide/advanced-state-management-with-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.
