|
1 | 1 | import useStore from "../../store/store";
|
2 | 2 | import DynamicFields from "./DynamicFields";
|
3 |
| -import { useState } from "react"; |
| 3 | +import { useState, useEffect } from "react"; |
4 | 4 |
|
5 | 5 | const QueryProp = ({ tab }: { tab: number }) => {
|
6 | 6 | const setQuery = useStore((state) => state.setQuery);
|
7 | 7 |
|
8 | 8 | const [queryInput, setQueryInput] = useState([{ key: "", value: "" }]);
|
9 | 9 |
|
10 |
| - // converts queryInput object into query state i.e URL format string (?pages=10&offset=20) |
11 |
| - const addQueries = () => { |
12 |
| - const queries = |
13 |
| - "?" + |
14 |
| - queryInput |
15 |
| - .filter((q) => q.key !== "" && q.value !== "") |
16 |
| - .map( |
17 |
| - (q) => `${encodeURIComponent(q.key)}=${encodeURIComponent(q.value)}` |
18 |
| - ) |
19 |
| - .join("&"); |
20 |
| - setQuery(queries); |
21 |
| - }; |
| 10 | + useEffect(() => { |
| 11 | + const queries = queryInput |
| 12 | + .filter((q) => q.key !== "" || q.value !== "") // Include if either is non-empty |
| 13 | + .map( |
| 14 | + (q) => |
| 15 | + `${encodeURIComponent(q.key)}=${encodeURIComponent( |
| 16 | + q.value |
| 17 | + )}`.replace(/=$/, "") // Remove "=" if the value is empty |
| 18 | + ) |
| 19 | + .join("&"); |
| 20 | + |
| 21 | + const queryString = queries ? `?${queries}` : ""; |
| 22 | + setQuery(queryString); |
| 23 | + }, [queryInput, setQuery]); |
| 24 | + |
| 25 | + |
22 | 26 | const clearQueries = () => {
|
23 | 27 | setQuery("");
|
24 | 28 | setQueryInput([{ key: "", value: "" }]);
|
25 | 29 | };
|
| 30 | + |
26 | 31 | return (
|
27 | 32 | <div className={`${tab == 1 ? "block" : "hidden"}`}>
|
28 | 33 | {queryInput[0].key !== "" && queryInput[0].value !== "" && (
|
29 |
| - <> |
30 |
| - <button |
31 |
| - className="bg-green-500 mt-2 ml-4 px-5 py-1 font-semibold text-white rounded-md" |
32 |
| - onClick={addQueries} |
33 |
| - > |
34 |
| - Add Queries |
35 |
| - </button> |
36 |
| - <button |
37 |
| - className="bg-red-500 mt-2 ml-4 px-5 py-1 font-semibold text-white rounded-md" |
38 |
| - onClick={clearQueries} |
39 |
| - > |
40 |
| - Clear Queries |
41 |
| - </button> |
| 34 | + <> |
| 35 | + <button |
| 36 | + className="bg-red-500 mt-2 ml-4 px-5 py-1 font-semibold text-white rounded-md" |
| 37 | + onClick={clearQueries} |
| 38 | + > |
| 39 | + Clear Queries |
| 40 | + </button> |
42 | 41 | </>
|
43 | 42 | )}
|
44 | 43 | <DynamicFields inputs={queryInput} setInputs={setQueryInput} />
|
|
0 commit comments