heroku/react-refetch

Using react-refetch with API object?

ipanasenko opened this issue · 9 comments

Hey, guys.

I have an API for some service, that is in its own module, and it has an API like this: api.list(), which returns a promise, that is resolved with list of users, let's say.

How do I use it with react-refetch? From what I see, I should specify url for request, but I would like to use already created API, that also does some data transformations.

You can set value to a Promise instead of setting a URL. Something like this:

connect(props => ({
  listFetch: {
    value: api.list()
  }
}))(MyComponent)

You might also want to consider setting comparison to control when this is refetched.

See https://github.com/heroku/react-refetch#identity-requests-static-data--transforming-responses for details.

@ryanbrainard thank you very much. I indeed saw identity requests part, I just didn't notice that I can provide a Promise to a value. Thanks!

@ryanbrainard what do you think about adding support for thenables? Right now we try to pass a thenable object instead of Promise instance, and it doesn't work properly. I can provide PR for this.

@ipanasenko I think that would be great!

Hey folks,

Could identity requests same be used for updates/overrides? e.g.

export default connect(props => ({
  likesFetch: {
    value: api.getLikes()
  },
  createLike: likeText => ({
    likeCreation: {
      value: api.createLike(likeText),
      andThen: () => ({
        likesFetch: {
          value: api.getLikes(),
          refreshing: true
        }
      })
    }
  }) 
}))(Likes);

sandbox here

I'm seeing that the update is not being called after creation. Is this possibly a bug?

I did it like this:

export default connect(props => ({
  likesFetch: {
    value: api.getLikes()
  },
  createLike: likeText => ({
    likesFetch: {
      value: api.createLike(likeText).then(api.getLikes),
      refreshing: true
    }
  })
}))(Likes);

But anyway, making identity requests to have all the same feature as normal requests would be awesome

Ah, I see! Thanks. Not quiet the same though, since andThen preserves the 'createLike' PromiseState and this clobbers it. Would love to see promises more fully supported.

Also, I couldn't get that to work. Had to end up doing the following:

export default connect(props => ({
  likesFetch: {
    value: api.getLikes()
  },
  like: likeText => {
    const likePromise = api.like(likeText);
    return {
      likeResponse: {
        value: likePromise
      },
      likesFetch: {
        value: likePromise,
        refreshing: true
      }
    };
  }
}))(LikesContainer);

Will sharing the promise cause problems with react-refetch?