rojass
rojass

Reputation: 37

Passing input value to fetch data not working

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

Answers (2)

simmer
simmer

Reputation: 2711

A few issues here:

  1. (major) Your 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.
  2. (major) Since your 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.
  3. (medium) It's a good idea to make your input "controlled" by setting its value to searchInput
  4. (minor) <input /> is a self-closing tag

Try 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

Ghulam Akbar
Ghulam Akbar

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

Related Questions