Home > Blockchain >  Pass data from searchbar into backend function
Pass data from searchbar into backend function

Time:04-12

The title says it all - I'm trying to send a word from a search bar to be consumed and processed in a backend function.

Any ideas on how this can be accomplished?

I'm using react and node/express for this

CodePudding user response:

you also can use jQuery.The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

CodePudding user response:

You can use the following method. The search term can be accessed in the backend from req.body. I have also used the debounce method so that the api won't be flooded if user continuously types in the search bar

import { useEffect, useState } from "react";
import debounce from "lodash.debounce";
import axios from "axios";

export default function App() {
  const [text, setText] = useState("");

  useEffect(() => {
    if (text.length > 0) {
      const payload = {
        query: text
      };
      axios
        .post("your_api_url_here", payload)
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }, [text]);

  const update = (e) => setText(e?.target?.value);
  const debouncedOnChange = debounce(update, 500); // delay to prevent bulk api call

  return (
    <div className="App">
      <input placeholder="Search" type="text" onChange={debouncedOnChange} />
    </div>
  );
}

CodePudding user response:

Whenever you decide it's the moment to send the value (either pressing a button or detecting a specific string) you can get the value of that element accessing document object and send it through a request to backend (maybe using axios)

  • Related