How to do this React Query thing without useEffect

Hi, here's some working code that I would love to remove the useEffect from. However if I just give the input text to the query directly, search results disappear when the user changes the search text because it creates a new query. Any ideas on an elegant way to solve this?
const [inputVal, setInputVal] = useState("");
const [text, setText] = useState("");

const {
data,
refetch,
// etc
} = useGetPostsPaginated({ text }); // this is a tRPC query

useEffect(() => {
if (text.length > 0) {
refetch();
}
}, [text, refetch]);

function handleSearch(e: React.FormEvent) {
e.preventDefault();
setText(inputVal);
}

return (
<>
<form onSubmit={handleSearch}>
<input value={inputVal} onChange={e => stInputVal(e.target.value)} />
<button>Submit</button>
</form>
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
</>
)
const [inputVal, setInputVal] = useState("");
const [text, setText] = useState("");

const {
data,
refetch,
// etc
} = useGetPostsPaginated({ text }); // this is a tRPC query

useEffect(() => {
if (text.length > 0) {
refetch();
}
}, [text, refetch]);

function handleSearch(e: React.FormEvent) {
e.preventDefault();
setText(inputVal);
}

return (
<>
<form onSubmit={handleSearch}>
<input value={inputVal} onChange={e => stInputVal(e.target.value)} />
<button>Submit</button>
</form>
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
</>
)
2 Replies
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Brendonovich
Brendonovich3y ago
Could you change from using a controlled input to an uncontrolled one, get the value of the input from the FormEvent and then set text to the input value?
Want results from more Discord servers?
Add your server