useNutritionAdvisor
export type messageType = 'text' | 'image' | 'response' | 'typing'
export interface ChatEntity {
type: messageType
message?: string
uri?: string
response?: PassioAdvisorResponse | null
}
export type SDKStatus = 'Success' | 'Error' | 'Init'
useNutritionAdvisor
import { useEffect, useState } from 'react'
import {
NutritionAdvisor,
PassioAdvisorMessageResultStatus,
} from '@passiolife/nutritionai-react-native-sdk-v3'
export const useNutritionAdvisor = () => {
const [configureStatus, setConfigureStatus] = useState<SDKStatus>('Init')
const [messages, setMessage] = useState<ChatEntity[]>([])
useEffect(() => {
const initializeNutritionAdvisor = async () => {
try {
const conversationResponse = await NutritionAdvisor.initConversation()
setConfigureStatus(
conversationResponse?.status === 'Success' ? 'Success' : 'Error'
) }
} catch (err) {
console.error(`PassioSDK Error ${err}`)
setConfigureStatus('Error')
}
}
initializeNutritionAdvisor()
}, [])
const handleAdvisorResponse = async (
response: PassioAdvisorMessageResultStatus | null,
message: string | undefined
) => {
setMessage((item) => {
if (response?.status === 'Success') {
const chatResponse: ChatEntity = {
type: 'response',
response: response.response,
}
return [...item.filter((it) => it.type !== 'typing'), chatResponse]
} else {
const chatResponse: ChatEntity = {
type: 'response',
response: null,
message: message,
}
return [...item.filter((it) => it.type !== 'typing'), chatResponse]
}
})
}
const sendMessage = async (message: string) => {
setMessage((item) => {
return [
...item,
{
type: 'text',
message: message,
},
{
type: 'typing',
},
]
})
const response = await NutritionAdvisor.sendMessage(message)
handleAdvisorResponse(response, message)
}
const sendImage = async (imgUrl: string) => {
setMessage((item) => {
return [
...item,
{
type: 'image',
uri: imgUrl,
},
{
type: 'typing',
},
]
})
const response = await NutritionAdvisor.sendImage(imgUrl)
handleAdvisorResponse(response, imgUrl)
}
return {
configureStatus,
messages,
sendMessage,
sendImage,
}
}
Last updated