/home/vianto5/realtylifestyleproperties.mx/wp-content/plugins/code-snippets/js/hooks
Edit: /home/vianto5/realtylifestyleproperties.mx/wp-content/plugins/code-snippets/js/hooks/useSnippets.ts (2640B)
import { useEffect, useMemo, useState } from 'react'
import { addQueryArgs } from '@wordpress/url'
import { handleUnknownError } from '../utils/errors'
import { isNetworkAdmin } from '../utils/general'
import { useAxios } from './useAxios'
import type { Snippet } from '../types/Snippet'
import type { SnippetsExport } from '../types/SnippetsExport'
import type { AxiosResponse, CreateAxiosDefaults } from 'axios'
const ROUTE_BASE = window.CODE_SNIPPETS?.restAPI.snippets
const AXIOS_CONFIG: CreateAxiosDefaults = {
headers: { 'X-WP-Nonce': window.CODE_SNIPPETS?.restAPI.nonce }
}
export interface SnippetsAPI {
fetchAll: (network?: boolean | null) => Promise
>
fetch: (snippetId: number, network?: boolean | null) => Promise>
create: (snippet: Snippet) => Promise>
update: (snippet: Snippet) => Promise>
delete: (snippet: Snippet) => Promise>
activate: (snippet: Snippet) => Promise>
deactivate: (snippet: Snippet) => Promise>
export: (snippet: Snippet) => Promise>
exportCode: (snippet: Snippet) => Promise>
}
const buildURL = ({ id, network }: Snippet, action?: string) =>
addQueryArgs(
[ROUTE_BASE, id, action].filter(Boolean).join('/'),
{ network: network ? true : undefined }
)
export const useSnippetsAPI = (): SnippetsAPI => {
const { get, post, del } = useAxios(AXIOS_CONFIG)
return useMemo((): SnippetsAPI => ({
fetchAll: network =>
get(addQueryArgs(ROUTE_BASE, { network })),
fetch: (snippetId, network) =>
get(addQueryArgs(`${ROUTE_BASE}/${snippetId}`, { network })),
create: snippet =>
post(`${ROUTE_BASE}`, snippet),
update: snippet =>
post(buildURL(snippet), snippet),
delete: (snippet: Snippet) =>
del(buildURL(snippet)),
activate: snippet =>
post(buildURL(snippet, 'activate')),
deactivate: snippet =>
post(buildURL(snippet, 'deactivate')),
export: snippet =>
get(buildURL(snippet, 'export')),
exportCode: snippet =>
get(buildURL(snippet, 'export-code'))
}), [get, post, del])
}
export const useSnippets = (): Snippet[] | undefined => {
const api = useSnippetsAPI()
const [snippets, setSnippets] = useState()
useEffect(() => {
if (!snippets) {
api.fetchAll(isNetworkAdmin())
.then(response => setSnippets(response.data))
.catch(handleUnknownError)
}
}, [api, snippets])
return snippets
}