Certifications
Gen AI Advanced
Bring it together

Bring it together

Now when you have the Front End and Back End in place, you need to combine the two to finalize the application.

See example below on how you can handle this:

import { useState } from 'react'
import { getOpenAIResponse } from '../openai'
import { saveConversation, getAllConversations } from '../fileStorage'
 
export default function Home() {
  const [messages, setMessages] = useState([])
  const [input, setInput] = useState('')
 
  const handleSendMessage = async () => {
    // Add user message to the state
    setMessages([...messages, { text: input, type: 'user' }])
 
    // Get OpenAI response
    const response = await getOpenAIResponse(input)
 
    // Save conversation to file storage
    saveConversation(input, response)
 
    // Add OpenAI response to the state
    setMessages([...messages, { text: response, type: 'bot' }])
 
    // Clear the input field
    setInput('')
  }
 
  const loadConversations = () => {
    const conversations = getAllConversations()
    setMessages(
      conversations.map(
        ({ userMessage, botResponse }) => (
          { text: userMessage, type: 'user' },
          { text: botResponse, type: 'bot' }
        ),
      ),
    )
  }
 
  return (
    <div>
      {/* Render messages and input field */}
      <div>
        {messages.map((message, index) => (
          <div key={index} className={message.type}>
            {message.text}
          </div>
        ))}
      </div>
      <input
        type="text"
        value={input}
        onChange={(e) => setInput(e.target.value)}
      />
      <button onClick={handleSendMessage}>Send</button>
      <button onClick={loadConversations}>Load Conversations</button>
    </div>
  )
}