Home > Software engineering >  How do I add variable to the POST body of the request
How do I add variable to the POST body of the request

Time:06-02

I'm trying to build a search and filter in react and material-ui. I have already implemented a client-side search. All I need for now is to add something to the below to pass a text string in the body of the request. This text should come from a TextField, but I have no idea on how to implement it correctly. If I do, it ends up being undefined when it changes as I can't seem to add it directly when states change. Even if I would get a result by adding a const, it usually would only load when the page loads but not on onInput.

The Search :

const SearchBar = ({setSearchQuery}) => (
  <form>
    <TextField
      id="search-bar"
      onInput={(e) => {
        setSearchQuery(e.target.value);
      }}
      variant="outlined"
      placeholder="Search..."
      size="small"
    />
  </form>
);

The export function :

const [tableData, setTableData] = useState([])

const [searchQuery, setSearchQuery] = useState("");

useEffect(() => {

const someVariable = "5"

const targeturl = "https://website.com/" someVariable "/-1";      

fetch(targeturl, {
method: 'post',
headers: { 'Content-Type': 'application/json' },
 })
.then((data) => data.json())
.then((data) => setTableData(data))

}, [])

const rows = tableData; 

...

<div className="dflex jusend">
    <SearchBar searchQuery={searchQuery} setSearchQuery={setSearchQuery} />
</div>

I tried adding a function that gets the search string from a TextField, but that doesn't work.

fetch(targeturl, {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: getQuery(searchQuery)
 })
.then((data) => data.json())
.then((data) => setTableData(data))

}

CodePudding user response:

you can send data in body of fetch request and also add dependency in useEffect:

useEffect(() => {

const someVariable = "5"

const targeturl = "https://website.com/" someVariable "/-1";      

fetch(targeturl, {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({searchQuery})
 })
.then((data) => data.json())
.then((data) => setTableData(data))

}, [searchQuery])
  • Related