import React from 'react' import apiFetch from '@wordpress/api-fetch' import { GoodsDescriptionSuggestion } from './model/models' type Suggestions = Record declare interface SuggestionsResponse { suggestions: Array } const unavailable = (productIds: Array): Suggestions => Object.fromEntries( productIds.map(id => [id, { status: 'UNAVAILABLE', description: null }]) ) const bySuggestedProduct = ({ suggestions, }: SuggestionsResponse): Suggestions => Object.fromEntries( suggestions.map(({ id, status, description }) => [ id, { status, description }, ]) ) export const useGoodsDescriptionSuggestions = (productIds: Array) => { const [suggestedProductIds] = React.useState(productIds) const [loading, setLoading] = React.useState(suggestedProductIds.length > 0) const [suggestions, setSuggestions] = React.useState({}) React.useEffect(() => { if (suggestedProductIds.length === 0) { return } let closed = false apiFetch({ path: '/posten-bring-checkout/goods-descriptions/suggestions', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ productIds: suggestedProductIds }), }) .then(bySuggestedProduct) .catch(() => unavailable(suggestedProductIds)) .then(fetched => { if (!closed) { setSuggestions(fetched) setLoading(false) } }) return () => { closed = true } }, [suggestedProductIds]) return { loading, suggestions } }