I want to send data through an API in a UI Extension using React.

Thank you in advance

I want to send data through an API in a UI Extension using React.i am facing this error

TypeError: i is not a function

at t.U (e263900d-d68d-4be7-a210-d19fc04831d6.js?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20250630T063335Z&X-Amz-SignedHeaders=host&X-Amz-Expires=28800&X-Amz-Credential=AKIAWQDZYH6KDTJIVD6M%2F20250630%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=340384d23c801723b87e3fb7029c3cbde988dbd35143349cb521ce1e5b667594:1:4711)

at t (index.js:403:30)

at Object.call (index.js:102:30)

at MessagePort.d (index.js:408:42) why i am facing this error

Hi @SagarTomar,

This issue can occur if you’re importing or passing a value incorrectly, perhaps you’re referencing a variable or object instead of a function. Double-check that the function you’re calling is actually a function. Also, review your imports and how you’re passing properties to ensure everything is set up correctly.

Thank you for response .

if i send hardcoded value still not working

const response = await fetchApi(‘https://mediumpurple-deer-340527.hostingersite.com/send-message’, {

method: 'POST',

headers: {

 'Content-Type': 'application/json',

},

body: JSON.stringify({

 number: "18315316612",

 portalId: "46022779",

 message: "hello",

}),

});

Hi @SagarTomar
To make API requests within a HubSpot UI Extension, you should use hubspot.fetch() instead of the native fetch() method.
I recommend reviewing the official documentation here:

I hope this helps! If it resolves your issue, please consider marking this as the accepted solution and giving it an upvote to assist others in the community as well.

Thanks!

if i am sending hardcode value same error is appering. the error is

72c72d32-09ab-45bf-9…f89deb5c56f468137:1 Error sending SMS: TypeError: i is not a function

at t.N (72c72d32-09ab-45bf-9…b5c56f468137:1:4633)

at t (index.js:403:30)

at Object.call (index.js:102:30)

at MessagePort.d (index.js:408:42)

N @ 72c72d32-09ab-45bf-9…f89deb5c56f468137:1

t @ index.js:403

call @ index.js:102

d @ index.js:408

Hi @SagarTomar

“Please share the top part of your file (imports and how fetchApi is defined), I believe there must be an error in importing the file.
Here are some tips -
Use fetchApi only inside UI extensions and import it correctly.
Use regular fetch() in non-extension code.”

I hope this will help you out. Please mark it as Solution Accepted and upvote to help another Community member.

Thanks!

import React, { useState, useEffect, useRef } from ‘react’;

import {

Button,

Modal,

ModalBody,

Text,

TextArea,

Box,

Flex,

hubspot,

} from ‘@hubspot/ui-extensions’;

// hubspot.extend(({ context, actions }) => {

// console.log(‘:white_check_mark: Available actions:’, actions);

// console.log(‘:white_check_mark: fetchHubSpotApi:’, actions.fetchHubSpotApi);

// console.log(‘:white_check_mark: Type of fetchHubSpotApi:’, typeof actions.fetchHubSpotApi);

// return (

// <Extension

// context={context}

// fetchProperties={actions.fetchCrmObjectProperties}

// fetchHubSpotApi={actions.fetchHubSpotApi} // :white_check_mark: correctly pass

// />

// );

// });

hubspot.extend(({ context, actions }) => {

console.log(‘:white_check_mark: Available actions:’, actions);

return (

\<Extension

  context={context}

  fetchProperties={actions.fetchCrmObjectProperties}

  // ❌ remove fetchHubSpotApi

/>

);

});

const Extension = ({ context, fetchProperties, fetchHubSpotApi }) => {

return (

\<Button

  overlay={

    \<Modal id="chatbot-modal" title="MCUTILITY" width="md">

      \<ModalBody>

        \<Box direction="column" gap="md" padding="md">

          \<ChatBotUI

            context={context}

            fetchProperties={fetchProperties}

            // fetchHubSpotApi={fetchHubSpotApi} // ✅ pass correctly

          />

        \</Box>

      \</ModalBody>

    \</Modal>

  }

>

  Send SMS

\</Button>

);

};

const ChatBotUI = ({ context, fetchProperties }) => {

const [messages, setMessages] = useState([

{ from: 'bot', text: 'Hi there! How can I assist you today?' },

]);

const refChatUi = useRef(null);

const [input, setInput] = useState(‘’);

const [contactDetails, setContactDetails] = useState(null);

const [loadingContact, setLoadingContact] = useState(true);

const [errorContact, setErrorContact] = useState(null);

const [sendingSMS, setSendingSMS] = useState(false);

const [smsError, setSmsError] = useState(null);

useEffect(() => {

const getContactData = async () => {

  if (

    context.crm &&

    context.crm.objectId &&

    context.crm.objectTypeId === '0-1'

  ) {

    try {

      setLoadingContact(true);

      const properties = await fetchProperties(\[

        'firstname',

        'lastname',

        'email',

        'phone',

        'company',

      ]);

      setContactDetails(properties);

    } catch (error) {

      setErrorContact('Failed to load contact details.');

    } finally {

      setLoadingContact(false);

    }

  } else {

    setErrorContact('Extension not running on a contact record.');

    setLoadingContact(false);

  }

};

getContactData();

}, [context, fetchProperties]);

useEffect(() => {

if (refChatUi.current) {

  refChatUi.current.scrollTop = refChatUi.current.scrollHeight;

}

}, [messages]);

const handleSend = async () => {

if (!input.trim()) return;

setMessages((prev) => […prev, { from: ‘user’, text: input }]);

if (!contactDetails || !contactDetails.phone) {

const err = 'Contact phone number not available.';

setSmsError(err);

setMessages((prev) => \[...prev, { from: 'bot', text: \`Error: ${err}\` }]);

setInput('');

return;

}

const phoneNumber = contactDetails.phone;

const portalId = context.portal?.id;

if (!portalId) {

const err = 'HubSpot portal ID not found.';

setSmsError(err);

setMessages((prev) => \[...prev, { from: 'bot', text: \`Error: ${err}\` }]);

setInput('');

return;

}

try {

setSendingSMS(true);

setSmsError(null);

// ✅ Call your own external API directly

const response = await fetch(‘https://mediumpurple-deer-340527.hostingersite.com/send-message’, {

method: ‘POST’, // :white_check_mark: Correct method

headers: {

'Content-Type': 'application/json',

},

body: JSON.stringify({

number: phoneNumber,

portalId,

message: input,

}),

});

const result = await response.json();

if (!response.ok) {

  throw new Error(result.message \|\| 'Failed to send SMS');

}

setMessages((prev) => \[

  ...prev,

  {

    from: 'bot',

    text: \`SMS sent to ${phoneNumber}. You said: "${input}".\`,

  },

]);

setInput('');

} catch (error) {

const err = \`Failed to send SMS: ${error.message}\`;

setSmsError(err);

setMessages((prev) => \[...prev, { from: 'bot', text: err }]);

} finally {

setSendingSMS(false);

}

};

return (

\<Box direction="column">

  \<Box

    padding="sm"

    style={{

      border: '1px solid #e0e0e0',

      borderRadius: '8px',

      marginBottom: '12px',

    }}

  >

    \<Text variant="small" style={{ fontWeight: 'bold' }}>

      Contact Details:

    \</Text>

    {loadingContact && \<Text variant="small">Loading contact...\</Text>}

    {errorContact && (

      \<Text variant="small" style={{ color: 'red' }}>

        {errorContact}

      \</Text>

    )}

    {contactDetails && (

      \<Box direction="column" gap="extraSmall">

        {contactDetails.firstname && (

          \<Text variant="small">

            First Name: {contactDetails.firstname}

          \</Text>

        )}

        {contactDetails.lastname && (

          \<Text variant="small">

            Last Name: {contactDetails.lastname}

          \</Text>

        )}

        {contactDetails.email && (

          \<Text variant="small">Email: {contactDetails.email}\</Text>

        )}

        {contactDetails.phone && (

          \<Text variant="small">Phone: {contactDetails.phone}\</Text>

        )}

        {contactDetails.company && (

          \<Text variant="small">Company: {contactDetails.company}\</Text>

        )}

      \</Box>

    )}

  \</Box>

  {sendingSMS && (

    \<Text variant="small" style={{ color: 'blue' }}>

      Sending SMS...

    \</Text>

  )}

  {smsError && (

    \<Text variant="small" style={{ color: 'red' }}>

      {smsError}

    \</Text>

  )}

  \<Box

    direction="column"

    ref={refChatUi}

    style={{

      height: '300px',

      overflowY: 'auto',

      padding: '8px',

      border: '1px solid #ddd',

      borderRadius: '8px',

      marginBottom: '12px',

    }}

  >

    {messages.map((msg, idx) => (

      \<Flex

        key={idx}

        justifyContent={msg.from === 'user' ? 'flex-end' : 'flex-start'}

      >

        \<Box

          padding="sm"

          style={{

            backgroundColor:

              msg.from === 'user' ? '#DCF8C6' : '#F1F0F0',

            borderRadius: '16px',

            maxWidth: '70%',

          }}

        >

          \<Text>{msg.text}\</Text>

        \</Box>

      \</Flex>

    ))}

  \</Box>

  \<Box direction="column" gap="xs">

    \<TextArea

      placeholder="Type your message..."

      value={input}

      onChange={(value) => setInput(value)}

      rows={2}

      disabled={sendingSMS}

    />

    \<Button onClick={handleSend} disabled={sendingSMS}>

      Send

    \</Button>

  \</Box>

\</Box>

);

};

thank you for your response this is my full code

Hi @SagarTomar

In this section, try using await fetchHubSpotApi, as we are inside the HubSpot UI extension, so we should use this, and it should work fine. That’s the best I can get from your code; the rest, I believe, you are already doing all good here.

I hope this will help you out. Please mark it as Solution Accepted and upvote to help another Community member.

Thanks!

thank you for response

dca557ab-453a-42d2-8…7e14ff94ca2f085ce:1 Refused to connect to ‘https://mediumpurple-deer-340527.hostingersite.com/send-message’ because it violates the following Content Security Policy directive: “connect-src none”.

N @ dca557ab-453a-42d2-8…7e14ff94ca2f085ce:1

t @ index.js:403

call @ index.js:102

d @ index.js:408

dca557ab-453a-42d2-8…7e14ff94ca2f085ce:1 Fetch API cannot load https://mediumpurple-deer-340527.hostingersite.com/send-message. Refused to connect because it violates the document’s Content Security Policy.

N @ dca557ab-453a-42d2-8…7e14ff94ca2f085ce:1

t @ index.js:403

call @ index.js:102

d @ index.js:408

now i am facing this error . this api written in laravel.please help me with this issue