Implement a button labelled "Set Content" to initiate the setting of complex objects within the state.
Refer the snippet below.
<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.
<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.
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.
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.
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>
)
}