This how-to guide follows on from using state to store notes. We advise you to read this guide before continuing.
Now that we're storing notes in app state, we might want to store a unique set of notes per Deskpro ticket. To do this, we can get the ticket ID using app events, and modify the storage key to include this.
Storing Notes by Deskpro Ticket ID
In order to get information about a ticket, we need to listen for an app event that provides the ticket "context" when our app is loaded. The best way to do this is to use the CHANGE
event for the following reasons:
When the app is first loaded, it will received a
CHANGE
eventWhen the app context changes, it will receive a
CHANGE
eventWhen the app is refreshed, it will receive a
CHANGE
event
This way we can guarantee that we're using the most up-to-date ticket information.
Ok, let's use the useDeskproAppEvents()
hook to register an onChange()
listener.
import { FC, useState } from "react";
import {
Button, Context,
GetStateResponse, SetStateResponse,
Stack,
TextArea, useDeskproAppClient, useDeskproAppEvents,
useInitialisedDeskproAppClient
} from "@deskpro/app-sdk";
export const Main: FC = () => {
const { client } = useDeskproAppClient();
// State to hold the ticket ID
const [ticketId, setTicketId] = useState<string|null>(null);
const [notes, setNotes] = useState<string>("");
useDeskproAppEvents({
// Listen for a "CHANGE" event and get the ticket ID from the context
onChange(context: Context) {
setTicketId(context.data.ticket.id);
},
});
useInitialisedDeskproAppClient((client) => {
client.getUserState<string>(`deskpro/my-app/notes/${ticketId}`)
.then((res: GetStateResponse<string>[]) => setNotes(res[0]?.data ?? ""))
;
}, [ticketId]);
const save = () => {
client?.setUserState<string>(`deskpro/my-app/notes/${ticketId}`, notes)
.then((res: SetStateResponse) => console.info(res.isSuccess))
;
};
return (
<Stack gap={4} vertical>
<label>
Notes
<TextArea
rows={4}
onChange={(e) => setNotes(e.target.value)}
value={notes}
/>
</label>
<Button text="Save" onClick={() => save()} />
</Stack>
);
}; copy
When our app receives a CHANGE
event, we extract the ticket ID from the app context and store it in component state. Later, we append the ticket ID to the app state key so notes are stored on a per Deskpro ticket basis.
Please log in or register to submit a comment.