Giter VIP home page Giter VIP logo

ava / use-http Goto Github PK

View Code? Open in Web Editor NEW
2.3K 2.3K 114.0 7.83 MB

🐶 React hook for making isomorphic http requests

Home Page: https://use-http.com

License: MIT License

TypeScript 99.13% JavaScript 0.87%
fetch fetch-data graphql http isomorphic mutation query react react-cache react-fetch-hook react-hook react-hooks react-suspense react-usefetch reacthook request rest-client ssr suspense usefetch

use-http's People

Contributors

alex-cory avatar alexburner avatar ashubham avatar cktang88 avatar dagda1 avatar dependabot[bot] avatar eagleera avatar g-plane avatar gerhut avatar goodrone avatar grafikart avatar greenkeeper[bot] avatar ignusg avatar jasonman34 avatar krishnasaga avatar marcod1419 avatar maxquinn avatar mcclayton avatar mogelbrod avatar mongrain avatar nanyang24 avatar patrickdelancy avatar romiem avatar rrostt avatar sbichenko avatar sgtwilko avatar theduc avatar toburger avatar vitaliyandrushko avatar yassienw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

use-http's Issues

onUpdate doesn't work with managed state

I wanna make new request. It works with onUpdate for unmanaged state.

const [isUpdate, updateState] = useState(false)
const {loading, error, data} = useFetch(
    'url',
    {
      timeout: 15000,
      onMount: true,
      onUpdate: [isUpdate],
      data: [],
    },
  )

But for managed state, it doesn't:

const [isUpdate, updateState] = useState(false)
  const [req, res] = useFetch('domain', {
      timeout: 15000,
      onUpdate: [isUpdate],
    },)
  async function fetch() {
    const data = await req.get(path)
    ....
  }

...
<TouchableOpacity
        onPress={() => {
          updateState(!isUpdate)
          fetch(true)
        }}>
<Text>reset</Text>
</TouchableOpacity>

After changing isUpdate and make another fetch() request. The result is still the same.

Next JS Support ?

Hello there... Does it support next.js? If so, then will you please provide an example?

Assign value to error on interceptors

Hi guys,

I would like to know if makes sense this possibility of assigning a value to the error on interceptors, see an example;

I need to apply a normalize function called callable depending on the type that is in types

This function would be applied before because of the data from useFetch destructuring should already have this value normalized.

The useFetch already has a possibility to set errors like the setError example below?

const { get, error, loading, data, abort } = useFetch(types[type].url,  {
    headers: getHeaders(types[type].id),
    loading: true,
    interceptors: {
      response: data => {
        try {
          types[type].callable(data)
        } catch(error) {
          setError(error)
        }
      }
    }
  }
)

React Native Support

It is really helpful if it can support react native as well.

But as of now it will not get any response, without throwing any errors or going to finally {} logic:

// useFetch.js (after transpile, in debugger)
// line 76
// logic ends here and no further
const response = yield fetch(url + query, Object.assign({ method }, options, { headers: Object.assign({ 'Content-Type': 'application/json' }, options.headers) }));

My component code is here and it works well in web.
This seems like a fetch issue for React Native, any ideas?

Feature Requests and Syntax Ideas

Abort

I've been toying around with different ways to implement this.

Ideas:

We can abort multiple http requests at once

const controller = new AbortController()
const todos = useFetch('http://example.com/todos', { controller })
todos.abort() // 🚫will error
const messages = useFetch('http://example.com/messages', { controller })
messages.abort() // 🚫will error
controller.abort()  // ✅

Individual Aborts

const todos = useFetch('http://example.com/todos')

todos.abort()

const messages = useFetch('http://example.com/messages')

messages.abort()

Typeahead usage
these are potential options for, if request1 is pending, and request2 is made, cancel request1. Or if they were set to 2, make 2 requests before canceling prior ones. Not sure the best way to handle this.

const todos = useFetch('http://example.com/todos', {
    deferred: 1,
    maxRequests: 1,
    limit: 1,
    typeahead: true,
    abort: 1,
})

function onChange(e) {
  todos.get(`?q=${e.target.value}`)
}

todos.data.map(todo => /* example */)

Syntax

I'm starting to like this syntax better, but what do you all think?

const todos = useFetch('http://example.com/todos')

todos.data
todos.get()
todos.post({
  name: 'cool'
})
todos.abort()
todos.loading

Avoid sending ContentType with GET requests

Describe the bug
useFetch sends a content type header (application/json by default) with GET requests. This should not happend and is making express fail by default

To Reproduce
Make a GET request without any options, use-http sends a content type header of "application/json"

Expected behavior
ContentType header should not be present when making get requests

Additional Response Data

Scenario

I'm creating a simple CRUD app with authentication. My API uses HTTP status codes and response headers to indicate certain information. Some status code examples:

  • Check if user is logged in when they aren't: GET /auth => 403
  • Login with invalid credentials: POST /auth => 403

Problem

Using use-http to make HTTP requests, I'm unable to determine the HTTP status or response headers of my requests, forcing me to modify my API to include these values in the response body (not so easy when consuming a third party API).

Proposal

Within the useFetch output, include some of the values from fetch's Response.
Some ideas:

  • Just pass back fetch's response object directly: const [myData, isLoading, error, request, response] = useFetch<IMyDataType>('/api/path')
  • Extract values from the response and pass them back individually: const { responseStatusText, responseHeaders, responseOk } = useFetch<IMyDataType>('/api/path')
  • Extract values from the response and pass them back in a custom response object: const { useHttpResponse } = useFetch<IMyDataType>('/api/path')

Is there a solution I'm missing? Or does anyone have any thoughts?

SSR Not working

I'm using version 0.1.68 but nothing is working. This is my codes:

import React from "react";
import useFetch from "use-http";

export default () => {
  const stories = useFetch(
    "https://hacker-news.firebaseio.com/v0/topstories.json",
    {
      onMount: true
    }
  );

  if (stories.error) return "Error";
  if (stories.loading) return "Loading";

  return <pre>{JSON.stringify(stories.data, null, 2)}</pre>;
};

New requests not fired when dependency array changes

Hi,

Thanks for the excellent work on this library!

I ran into some issues today, and I'm not sure that this is because of some bug, or simply because I have misunderstood how the API is supposed to work. The case has to do with firing new requests as entries in the dependency array changes.

For instance, I was expecting the following to fire a new request whenever id changes:

const stuff = useFetch(`/user${id}.json`, [id]);

What happens is that the request is initially fired on mount, but as id changes, nothing happens.

I've probably misunderstood how this is supposed to work, but if not then this might be some bug that I'm hitting. I have a complete example reproducing it available here: https://codesandbox.io/s/usefetch-dependency-array-slsb9?fontsize=14&hidenavigation=1&theme=dark

Thanks,
Jesper

An in-range update of eslint-plugin-jest is breaking the build 🚨

The devDependency eslint-plugin-jest was updated from 22.9.0 to 22.10.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-jest is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: test: Your tests failed on CircleCI (Details).

Release Notes for v22.10.0

22.10.0 (2019-07-17)

Features

Commits

The new version differs by 7 commits.

  • 28bd1dc feat(rules): adds no-if rule (#293)
  • 7ebdc0e chore: enforce import destructure order
  • 31c7cef chore: convert to import/export (#302)
  • 9f858cb chore: delete tests instead of ignoring them with babel
  • c595ba0 chore: do not include tests in published tarball
  • 4b4eb78 chore: fix lint error in md file
  • d3ea720 chore(docs): fix typo (#304)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepo:

    • The devDependency react was updated from 16.8.6 to 16.9.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: test: Your tests failed on CircleCI (Details).

Release Notes for 16.9.0 (August 8, 2019)

React

  • Add <React.Profiler> API for gathering performance measurements programmatically. (@bvaughn in #15172)
  • Remove unstable_ConcurrentMode in favor of unstable_createRoot. (@acdlite in #15532)

React DOM

React DOM Server

  • Fix incorrect output for camelCase custom CSS property names. (@bedakb in #16167)

React Test Utilities and Test Renderer

Artifacts

• react: https://unpkg.com/[email protected]/umd/
• react-art: https://unpkg.com/[email protected]/umd/
• react-dom: https://unpkg.com/[email protected]/umd/
• react-is: https://unpkg.com/[email protected]/umd/
• react-test-renderer: https://unpkg.com/[email protected]/umd/
• scheduler: https://unpkg.com/[email protected]/umd/

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Access the `.fetch` response directly to check for `response.ok` ?

Hi there!

Great work on the library- It looks to have almost all of what we need, but I've been playing with it and I've found an edge-case that I'd love some help with.

In our current implementations of our own hand-rolled useFetch, we have something that checks for any response.status that is not in the 200-299 range, ie: !response.ok:

const isOK = response => {
  if (!response.ok) {
    throw response
  }

  return response
}

const toJSON = response => response.json()

return fetch(`${config.BASE_API}/${endpoint}`, finalHeaders)
         .then(isOK)
         .then(toJSON)

This is so that we can basically call anything that's not a "200" an "error", as far as our front-end is concerned. We've got cases in our backend where we'd be receiving 422's, or 401's as responses, and since fetch doesn't error on those by default, we check for response.ok

Unfortunately due to the fact that use-http does all the response parsing and checking internally, by the time I get to the response data in the interceptors, I've already lost the response.ok & response.status objects etc.

Is there a way around this with the current implementation? It'd be nice if there was a way to specify interceptions even earlier, for this kind of situation, so that our 422's return to the error object rather than the data one.

Alternatively, happy to discuss other ways to solve this issue, even if I'm going about this kind of wrong.

Thanks!

useGet not working from 0.1.66 version

Last working version is 0.1.65. Situation looks like url has not been passed to request function, because request goes to current location(localhost).

Example of use:
const [users, usersLoading] = useGet('https://api.example.com/v2/users', { onMount: true })

An in-range update of use-ssr is breaking the build 🚨

The dependency use-ssr was updated from 1.0.18 to 1.0.19.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

use-ssr is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ci/circleci: test: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

onUpdate doesn't work

Hi,
I try the pagination example in my App but the fetch is done one time only on onMount. When I update page state nothing is done. Checking the Network tab in Google Chrome DevTools any other request is done.
This is my code

export default function Reservation() {
  const [page, setPage] = useState(1);

  const { loading, error, data: reservations } = useFetch(
    {
      path: `${endpointShuttles}?page=${page}`,
      onNewData: (currReservations, newReservations) => [...currReservations, ...newReservations.data],
      data: [],
    },
    [page],
  ); // onMount AND onUpdate whenever `page` changes

  // Used to test if useEffect is fired
  useEffect(() => console.log('useEffect page', page), [page]);

  return (
    <>
      <h1>Pagination</h1>
      {error && 'Error!'}

      <ul>{reservations && reservations.map((user, i) => <li key={i}>{user.shuttleCode}</li>)}</ul>
      <button type="submit" onClick={() => setPage(page + 1)}>
        {loading ? 'Loading...' : 'Load Data'}
      </button>
    </>
  );
}

The server return 200 with the correct data.
The useEffect added to test if page change is fired and console.log woks fine.
In upper component I use Provider with some options and custom interceptors but in the request interceptor the console.log is fired only at onMount.

It seems that the change of page state is not triggered.

Someone have any idea?

Thanks in advance,
Samuele

Feature request: consider allowing url to be undefined at init

Hello! ✋

The use case for the subkject is that right now I cannot do this:

let [request, response] = useFetch(); // useFetch init

const f = async () => await request.get('/unknown-endpoint-url-at-usefetch-init');
useEffect(() => f());

Instead I have to init with the bare minimum:

let [request, response] = useFetch('/'); // useFetch init

const f = async () => await request.get('unknown-endpoint-url-at-usefetch-init');
useEffect(() => f());

but that might be inconsistent with the rest of the request.get() calls across the app.

An empty string, such as useFetch('') would also be awesome to have.

I'm aware that most of the time init is done by passing something like /api, or the entire hostname for production, but for local development it's more ergonomice to not to have to separate the URL only to conform to useFetch's non-empty string contract.

What would be the way to pass cookies with requests?

Is there a way to pass cookies with requests?
In axios, for example, one would do someting like this:

axios.create({
  withCredentials: true
})

And, using Fetch Api:

fetch('https://example.com', {
  credentials: 'include'  
})

Is there an option to send and recieve cookies to/from the server?

Error should be reseted in every request.

Hi!

useHttp is really easy and cool to use. Congrats!
I would like to expose an issue I'm experimenting. I have something like this:

function SomeContainer() {
  const { error, request } = useFetch('https://...');
  const [data, setData] = useState(null);
  const [query, setQuery] = useState({ page: 1 });

  useEffect(() => {
    // ... A wrapper to allow using async/await
    const serializedQuery = queryString.stringify(query);
    const data = await request.get(`/some/endpoint/${serializedQuery}`);
    setData(data);
  }, [request, query]);

  const onQueryChange = nextQuery => {
    setQuery(nextQuery);
  };

  if (error) {
    return 'Something went wrong';
  }
  if (loading) {
    return 'Loading ...';
  }
  return <SomeDataComponent data={data}  onQueryChange={onQueryChange} />
}

Suppose that:

  1. The user has internet connection. Everything works fine. The result is that 'Loading ...' text appears first and then SomeDataComponent is rendered.
  2. The user lose connection.
  3. The user modifies the query and onQueryChange is called causing a re-render. That re-render executes the useEffect that will make a new fetch. The result of that fetch will be an error and we will see the text 'Something went wrong' in the screen.
  4. The user is online again.
  5. The user modify the query again so a new re-fetch is performed. In this scenario, in which the internet is reachable, we won't see SomeDataComponent rendered again. Instead we will stuck on 'Something went wrong'.

So to sum up: the error state is not reseted across requests calls.

An in-range update of @types/react is breaking the build 🚨

The devDependency @types/react was updated from 16.8.23 to 16.8.24.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: test: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @typescript-eslint/parser is breaking the build 🚨

The devDependency @typescript-eslint/parser was updated from 2.19.0 to 2.19.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@typescript-eslint/parser is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: test: Your tests failed on CircleCI (Details).

Release Notes for v2.19.1

2.19.1 (2020-02-10)

Bug Fixes

  • eslint-plugin: [unbound-method] blacklist a few unbound natives (#1562) (4670aab)
  • typescript-estree: ts returning wrong file with project references (#1575) (4c12dac)
Commits

The new version differs by 5 commits.

  • 1c8f0df chore: publish v2.19.1
  • 4c12dac fix(typescript-estree): ts returning wrong file with project references (#1575)
  • e9cf734 docs(eslint-plugin): fix typo in readme
  • 10d86b1 docs(eslint-plugin): [no-dupe-class-members] fix typo (#1566)
  • 4670aab fix(eslint-plugin): [unbound-method] blacklist a few unbound natives (#1562)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/react is breaking the build 🚨

The devDependency @types/react was updated from 16.8.18 to 16.8.19.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: test: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Trigger new request on url change

Currently I can't figure out a short and simple way to fetch data onMount and when the url changes.

The code below only triggers on mount, and looking at the docs (and source code) it doesn't seem like useGet takes a dependency array (like useEffect does) that indicates when the effect should execute again, is there some other option to get it re-run on url change as well as mount? Am I missing some other trivial way of accomplishing this?

import {useGet} from 'use-http'

function Todos(props) {
  const options = {
    onMount: true // will fire on componentDidMount
  }

  const todos = useFetch('https://example.com/todos/' + props.someID, options)

  return (
    <>
      {request.error && 'Error!'}
      {request.loading && 'Loading...'}
      {(todos.data || []).length > 0 && todos.data.map(todo => (
        <div key={todo.id}>{todo.title}</div>
      )}
    </>
  )
}

An in-range update of @types/jest is breaking the build 🚨

The devDependency @types/jest was updated from 24.0.16 to 24.0.17.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/jest is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • now: Deployment has failed (error: #b92DczE) (Details).
  • ci/circleci: test: Your tests passed on CircleCI! (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/react is breaking the build 🚨

The devDependency @types/react was updated from 16.8.21 to 16.8.22.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: test: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

is the graphql support worth maintaining

I hope this question does not come across as rude, it really is not meant to be.

I did a spike with GraphQL a while ago but I'm sort of curious where you see use-http fit into the ecosystem.

If I am using apollo or urql, would I not just use that?

Please feel free to shoot me down. This is just me being curious.

Create-react-app linting question

This isn't technically an issue with use-http (which I'm currently in love with for everything fetch-related) but in create-react-app, following the basic usage example create-react-app default linting shows the error React Hook useEffect has a missing dependency: 'initializeTodos'. Either include it or remove the dependency array react-hooks/exhaustive-deps. If I follow this guidance, the error changes to The 'initializeTodos' function makes the dependencies of useEffect Hook (at line 53) change on every render. Move it inside the useEffect callback. Alternatively, wrap the 'initializeTodos' definition into its own useCallback() Hook react-hooks/exhaustive-deps.

The example seems to work exactly as expected without adding to the dependency array, but I'm wondering if this breaks best practices. Is the linter being too fussy? Or should I be modifying the example to follow this rule?

Apologies if this shouldn't be an issue, I can re-post to stackoverflow.com if recommended. Many thanks for this great module!

Window is not defined

When used with Next.js and trying to reload a page from bowser, get following error:

ReferenceError: window is not defined
    at /Users/user/workspace/project1/node_modules/use-http/src/useFetch.ts:61:30
    at useFetch (/Users/user/workspace/project1/node_modules/use-http/src/useFetch.ts:129:27)
    at Reports (/Users/user/workspace/project1/build/server/static/development/pages/reports.js:685:76)
    at processChild (/Users/user/workspace/project1/node_modules/react-dom/cjs/react-dom-server.node.development.js:2888:14)
    at resolve (/Users/user/workspace/project1/node_modules/react-dom/cjs/react-dom-server.node.development.js:2812:5)
    at ReactDOMServerRenderer.render (/Users/user/workspace/project1/node_modules/react-dom/cjs/react-dom-server.node.development.js:3202:22)
    at ReactDOMServerRenderer.read (/Users/user/workspace/project1/node_modules/react-dom/cjs/react-dom-server.node.development.js:3161:29)
    at renderToString (/Users/user/workspace/project1/node_modules/react-dom/cjs/react-dom-server.node.development.js:3646:27)
    at render (/Users/user/workspace/project1/node_modules/next-server/dist/server/render.js:86:16)
    at renderPage (/Users/user/workspace/project1/node_modules/next-server/dist/server/render.js:211:20)
    at Function.value (/Users/user/workspace/project1/build/server/static/development/pages/_document.js:555:41)
    at Object.loadGetInitialProps (/Users/user/workspace/project1/node_modules/next-server/dist/lib/utils.js:42:35)
    at Object.renderToHTML (/Users/user/workspace/project1/node_modules/next-server/dist/server/render.js:218:36)

Uncaught Error in create-react-app

package.json:
"dependencies": {
"node-sass": "^4.12.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"use-http": "^0.1.62"
},

App.js:
import {useGet} from 'use-http';,

console panel:
Uncaught Error: Cannot find module 'idempotent-babel-polyfill'
at webpackEmptyContext (dist sync:2)
at f (index.js:14)
at p (index.js:29)
at Object.push../node_modules/use-http/dist/index.js.parcelRequire.RaX2 (index.js:62)
at f (index.js:23)
at p (index.js:29)
at Object.push../node_modules/use-http/dist/index.js.parcelRequire.Focm../useFetch (index.js:513)
at f (index.js:23)
at push../node_modules/use-http/dist/index.js.parcelRequire.RaX2 (index.js:42)
at Object../node_modules/use-http/dist/index.js (index.js:56)
at webpack_require (bootstrap:781)
at fn (bootstrap:149)
at Module../src/App.js (App.js:4)
at webpack_require (bootstrap:781)
at fn (bootstrap:149)
at Module../src/index.js (App.scss?2f5e:45)
at webpack_require (bootstrap:781)
at fn (bootstrap:149)
at Object.0 (serviceWorker.js:135)
at webpack_require (bootstrap:781)
at checkDeferredModules (bootstrap:45)
at Array.webpackJsonpCallback [as push] (bootstrap:32)
at main.chunk.js:1

error should be set when server response with an error

Describe the bug
When the server respond with an error (like 500 for example), data should be null and error should be the error.

Expected behavior
When calling fetch, response should be check with response.ok, if response is not ok, error should be set, not data.

Unexpected error

Hello I have an issue when using the useFetch hook to fire an http call.
After calling the hook on mount, the data prop is empty and I get the following in the error prop: TypeError: "NetworkError when attempting to fetch resource.

In the browser console the network call succeeded with code 200 and returns a valid JSON response.

Am I missing something the error doesn't tell me ? Or could it be a bug ?

Retry request in interceptors response

Usually servers handles token expiration and then with 401 response tells the client to refresh token.
In the examples this is handled in request interceptor, but is there a way to handle it response and retry all failed requests?

SSR - Weird issue with 'loading'

Describe the bug
Server side, I'm getting loading === true even if I'm not firing any request.
I tried putting { onMount: false, loading: false }.

Expected behavior
Loading should be false if no request is made. Moreover, it seems the lib does not do anything server side, so loading should be ever set.

How to trigger a refresh?

How would I trigger an update or requery of data?

I have a data table which I load with initial data I get using useFetch. Then in that table I have a modal to create a new item. I'm trying to re-load my dataTable when the new item is created.

I tried passing get as a prop to my form so on submit I'd call get() but get returns undefined.

This is what I have so far

  const { request, response, loading, error, data, get } = useFetch(
    `${apiPath}/mydata`,
    {
      // accepts all `fetch` options
      data: [] // default for `data` will be an array instead of undefined
    },
    []
  );

  const tableData = useMemo(
    () => (data || []).map(r => ({ ...r, questions: r.questions.length })),
    [data]
  );

  // Handle different api states
  // if (networkStatus === 4) return 'Refetching!';
  if (loading) return <p>Loading...</p>;
  if (error) throw Error(error);

  // React table requires memoized data
  // Return table with data
  return (
    <Box padding={1}>
      <ReactTable
        columns={columns}
        data={tableData}
        component={
          <FullScreenModal
            title="Create New ScoreCard"
            content={<ScoreCardForm toggleScorecardForm={toggleModal} />}
            open={isShowing}
            toggle={toggleModal}
            handleRefresh={get}
          />
        }
      />
    </Box>

Provider interceptor uses cached values?

I have created a custom Provider with (global) options to send certain headers on all requests via an interceptor. This interceptor should get a value from a context and send it with the headers, but it doesn't seem to update to the new value.

Created a CodeSandbox here

When you run it and open inspector to check the network calls, you can see that the x-token header remains null on each call, even though the 'token' value is updated in the context as showed in the console and on the component render.

The funny thing is, if I place the exact same interceptor code in the useFetch hook itself, it does send the correct header value.
Like so:

	const [request, response] = useFetch({
		interceptors: {
			request: options => {
				console.log("Interceptor called with token", state.token);
				options.headers["x-token"] = state.token;
				return options;
			}
		}
	});

Async response

https://codesandbox.io/embed/usefetch-provider-requestresponse-interceptors-tg56u

@alex-cory I'm quite sure this is not necessarily a bug but rather conceptual issue I've run into:
Weirdly, the first time an async request fires my console.log(response) (L16) returns an empty object {}. Only if I run the request again I'll get the actual Response. Could you lead me in the right direction on how to retrieve the response once it's here and do something with it?

What I'm trying to achieve:
Our API provides an endpoint for submitting form data.
Now if server-side validation fails, the response will have the exact same keys as my request payload had, except there will be error messages as values. If there are errors, the response status code will be 400. Now what I'm trying to do is to somehow find out if !response.ok or response.status === 400 (from the response), so I can map potential errors to actual error components in my UI.

I've seen similar issues (accessing response from fetch) but I'm not sure why I would need an interceptor in this case.

How to fetch multiple URLs (non-constant number) at once?

Say I need to fetch a list of remote resources, while the length on the list depends on the current props. (How) can I achieve that with use-http? As far as I understand the documentation of react, the number of hooks in a component needs to be constant.

Weird types

Describe the bug

export interface ReqBase<TData> {
    data: TData | undefined;
    loading: boolean;
    error: Error;
}

That should be replaced with

type ReqBase<TData> = 
  | {
    data: undefined.
    error: undefined,
    loading: false,
  }
  | {
    data: TData,
    error: undefined,
    loading: true,
  }
  | {
    data: undefined,
    error: Error,
    loading: true,
  };

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.