diff --git a/src/ChatBot.js b/src/ChatBot.js index f70f64e..663349c 100644 --- a/src/ChatBot.js +++ b/src/ChatBot.js @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useState, useEffect } from 'react'; import styles from './ChatBot.module.css'; const ChatBot = () => { @@ -17,6 +17,23 @@ const ChatBot = () => { const [input, setInput] = useState(''); const [isLoading, setIsLoading] = useState(false); + useEffect(() => { + if (!localStorage.getItem('session')) { + function generateUUID() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + const r = Math.random() * 16 | 0; + const v = c === 'x' ? r : (r & 0x3 | 0x8); + return v.toString(16); + }); + } + + const sessionId = generateUUID(); + const dateNow = new Date().toISOString(); + + localStorage.setItem('session', JSON.stringify({ sessionId: sessionId, lastSeen: dateNow})) + } + }, []); + const sendMessage = async (textOverride = null) => { const message = textOverride || input.trim(); if (message === '') return; @@ -26,22 +43,23 @@ const ChatBot = () => { { sender: 'user', text: message, time: getTime() }, ...messages, ]; + setMessages(newMessages); setInput(''); setIsLoading(true); try { // Send to backend - const response = await fetch('https://n8n.kediritechnopark.my.id/webhook/master-agent/ask' , { + const response = await fetch('https://n8n.kediritechnopark.my.id/webhook/master-agent/ask', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ pertanyaan: newMessages }), + body: JSON.stringify({ pertanyaan: newMessages, sessionId: JSON.parse(localStorage.getItem('session')).sessionId, lastSeen: new Date().toISOString() }), }); if (!response.ok) throw new Error('Network response was not ok'); const data = await response.json(); - console.log(data) + console.log(data) // Assuming your backend sends back something like: { answer: "text" } // Adjust this according to your actual response shape const botAnswer = data[0].output || 'Maaf, saya tidak mengerti.'; @@ -101,7 +119,6 @@ const ChatBot = () => { )}