import { useState } from "react" import { useSWRConfig } from "swr" import { backendApi, getAssetsListKey } from "infra/backend-api" import { ASSETS_DASHBOARD_LIST_PARAMS } from "../config/assets.config" import { toError } from "../lib/to-error" import type { CreateAssetAction, CreateAssetInput } from "../types/assets-api.type" /** * Сценарий создания asset с обновлением списка. */ export const useCreateAsset = (): CreateAssetAction => { const { mutate } = useSWRConfig() const [error, setError] = useState(null) const [isCreating, setIsCreating] = useState(false) const createAsset = async (input: CreateAssetInput) => { setError(null) setIsCreating(true) try { const createdAsset = await backendApi.assets.createAsset(input) await mutate(getAssetsListKey(ASSETS_DASHBOARD_LIST_PARAMS)) return createdAsset } catch (caughtError) { const nextError = toError(caughtError) setError(nextError) throw nextError } finally { setIsCreating(false) } } return { createAsset, error, isCreating, } }