App.js 1.6 KB
import React, {Fragment, useState} from "react";
import { Client } from "elasticsearch"
import "./App.css";

function App() {

  const [answer, setAnswer] = useState('');
  const [inputValue, setInputValue] = useState('');

  const client = new Client({
    host: 'http://localhost:9200'
  });

  const onKeyUpHandler = async (event) => {
    if (event.charCode === 13) {
      setInputValue(event.target.value);

      if (inputValue !== '' || inputValue !== undefined || inputValue.length !== 0) {
        console.log(inputValue);
        try {
          const result = await client.search({
            index: "wiki-test4",
            body: {
              query: {
                match: {
                  "질문": inputValue
                }
              }
            }
          });

          if (result !== null || result !== undefined || result.length !== 0) {
            setAnswer(result.hits.hits);
          }
        } catch (error) {
          console.log(error);
        }
      }
    }
  }

  const showAnswer = (answer) => {
    return (
        <div>
          <b>{answer !== undefined ? answer._source.정답 : 'loading ....'}</b>
        </div>
    )
  }

  return (
      <div className="App">
        <header className="App-header">
          <Fragment>
            Ask a Question
            <input size="80" onKeyPress={onKeyUpHandler}/>
            <div>
            -- Answers --
              <div>
                {answer === '' ? " loading answer..." : showAnswer(answer[0])}
              </div>
            </div>
          </Fragment>
        </header>
      </div>
  );
}

export default App;