use-http icon indicating copy to clipboard operation
use-http copied to clipboard

useFetch adds slash to path

Open creotip opened this issue 3 years ago • 3 comments

Describe the bug I used an example from the docs. There is prepended slash to query value that is appended to the URL.

for example: https://api.github.com/search/repositories?q=/some_value

should be: https://api.github.com/search/repositories?q=some_value

How to remove this slash or avoid this?

const { get, abort, loading, data: repos } = useFetch('https://api.github.com/search/repositories?q=')

// the line below is not isomorphic, but for simplicity we're using the browsers `encodeURI`
const searchGithubRepos = e => get(encodeURI(e.target.value))

<>
  <input onChange={searchGithubRepos} />
  <button onClick={abort}>Abort</button>
  {loading ? 'Loading...' : repos?.data?.items?.map(repo => (
    <div key={repo.id}>{repo.name}</div>
  ))}
</>

⚠️ SANDBOX ⚠️ https://codesandbox.io/s/intelligent-engelbart-oz206?file=/src/App.js

To Reproduce Steps to reproduce the behavior:

  1. Search for a value
  2. check the network

Expected behavior should be: https://api.github.com/search/repositories?q=some_value

creotip avatar May 23 '21 22:05 creotip

Hi,

(not the author just someone who uses this library!)

Try changing the code to be:

const { get, abort, loading, data: repos } = useFetch('https://api.github.com/search/repositories')

// the line below is not isomorphic, but for simplicity we're using the browsers `encodeURI`
const searchGithubRepos = e => get('?q='+encodeURI(e.target.value))

<>
  <input onChange={searchGithubRepos} />
  <button onClick={abort}>Abort</button>
  {loading ? 'Loading...' : repos?.data?.items?.map(repo => (
    <div key={repo.id}>{repo.name}</div>
  ))}
</>

Probably you should try to avoid using the e.target.value in the get, and insert the value in like you can see from the paging example ( see https://use-http.com/#/?id=pagination-with-provider ). As long as that value is in state, this should work.

sgtwilko avatar Jul 28 '21 17:07 sgtwilko

@creotip were you able to get this resolved from https://github.com/sgtwilko/use-http/commit/7952bd7018136b6b8344856ccf798d9f87eaa558?

alex-cory avatar Aug 11 '21 19:08 alex-cory

Hey a have a similar use case where a slash is prepended to the other http method I use:

const { data: pages = [], loading, del } = useFetch(
    "store/pages/",
    { cachePolicy: "no-cache" },
    []
  );

  async function destroy(slug) {
    await del(`${slug}/`);
  }

The reason I don't use store/pages is that my Django backend force a slash at the and and does a redirect to URL ending with /.

Then the del is trying to use //${slug}/.

Any workaround for this?

aambrozkiewicz avatar May 20 '22 12:05 aambrozkiewicz