Reputation: 37
I am fetching a csv from back-end. If I enter my ${baseURL}example.com
I can fetch data. But ${baseURL}{searchInput}
not works. There is 500 error.Input is passed as {searchInput}
.
const [csv, getcsv] = useState([]);
const [searchInput, setSearchInput] = useState("");
const fetchIt = useCallback(() => {
const baseURL = `http://localhost:3000/downloadIt?data=`;
axios
.get(`${baseURL}${searchInput}`)
.then((response) => {
getcsv(response.data);
})
.catch((error) => {
console.log(error);
});
}, []);
const handleChange = (event) => {
setSearchInput(event.target.value);
};
useEffect(() => {
fetchIt();
}, [fetchIt]);
return (
<div>
<h1>{csv}</h1>
<input onChange={handleChange}></input>
<h1>{searchInput}</h1>
<button>
<a href={csv}>Download</a>
</button>
</div>
);
Upvotes: 1
Views: 160
Reputation: 2711
A few issues here:
useEffect
hook runs fetchIt()
immediately, instead of waiting for searchInput
to have a value set. You're thus calling fetchIt
with a query string of ?data=
, and if your backend code can't gracefully handle that, you'll get a 500.useEffect
hook doesn't have searchInput
in its dependency array, it's not going to re-run whenever searchInput
changes. Add searchInput
as a dependency for that hook.input
"controlled" by setting its value to searchInput
<input />
is a self-closing tagTry this:
const [csv, getcsv] = useState([]);
const [searchInput, setSearchInput] = useState('');
const fetchIt = useCallback(() => {
const baseURL = 'http://localhost:3000/downloadIt?data=';
axios
.get(`${baseURL}${searchInput}`)
.then((response) => {
getcsv(response.data);
})
.catch((error) => {
console.log(error);
});
}, []);
const handleChange = (event) => {
setSearchInput(event.target.value);
};
useEffect(() => {
if (searchInput) {
fetchIt();
}
}, [fetchIt, searchInput]);
return (
<div>
<input onChange={handleChange} value={searchInput} />
<a href={csv}>Download CSV</a>
<code><pre>{csv}</pre></code>
</div>
);
Upvotes: 1
Reputation: 549
Try to console the output for
${baseURL}{searchInput}
I guess there might be slash issue in uri-segment. If not, this is move you one step towards your solution.
Upvotes: 0