Git Product home page Git Product logo

react-refetch's Issues

Offline Support

I'm working on a project that needs offline support and I don't want to use Flux, because all state is saved on server-side and I don't wanna duplicate/manage local state.

Would be awesome if we can provide our own implementation of handleResponse, so we can implement something like this:

// myOwnHandleResponse.js

import localforage from 'localforage';

const getRequestId = request => {
  // TODO: md5 or something like that :P
  return `${request.url}.${request.method}.${JSON.stringify(request.headers)}`;
};

// On response success update offline cache and return json
// On response failure warn and return the cached json
const handleResponse = (request, response) => {
  const requestId = getRequestId(request);
  if (response.status >= 200 && response.status < 300) { // Or response.ok
    const json = response.json();
    // localforage.setItem() resolves the value that was set :)
    return localforage.setItem(requestId, json).catch(error => {
      console.warn('Failed to update offline cache', { requestId, request, error });
      return json;
    });
  } else {
    return localforage.getItem(requestId);
  }
};

export default handleResponse;

We'll need to implement a timeout in React Refetch and implement a way to handle POST/PUT/DELETE requests.
It's just the initial idea. Toughts?

Supply custom fetch() implementation

It would be great if a custom fetch() implementation could be supplied to React Refetch. My usecase would be not using a completely custom implementation (although I think that could be useful, too), but doing something like this:

function customFetch (input, init = {}) {
  init.credentials = 'include'
  // do something on the input, too
  return window.fetch(input, init)
  .then(response => preprocess(response))
}

As well as implementing a kind of caching proxy that maintains a cache of responses and provides them directly from memory if Refetch asks for them based on some conditions (say, time since last request for that url, or window.onLine === false, or the heartbeat signal we use to check for effective offlineness, etc).

No way to access json value of an rejected request

My server returns status 400 (bad request) intentionally for bad data in a form, and I wish to read the json body that comes along with the response, explaining where that error is and what is it.
It seems the promise API does not allow me to read the error? Please help..
(I also tried messing around with Response object, and reading the json() stream, but no success)

screen shot 2016-02-02 at 11 23 06 am

image

Feature request: Query params

Nice library, thanks for creating it!

What do you think about adding some convenience features?

Url query params

connect((props) => ({
  data: {
    url: "/api/data",
    query: { from: props.from, limit: props.limit }  // => "/api/data?from=xxx&limit=yyy
  }
}))(Component)

Easy way to register to for a one time promise callback?

Rendering different promise statuses (pending, setteled, etc) is easy (yay!).
Performing a function one-time once a promise settles seems hard.
It's very common that I want to perform some logic when a promise is settled - for example:

  • forms (load data into state): fetch form data, once available, setState({ data: value }).
  • forms (post data, then do something): when submitting a form - on success, redirect to so other page (with react-router), or then - show success toaster.

if i do this:

  // no good for me
  componentWillReceiveProps(nextProps) {
    nextProps.fetchAccountPs.then(account => this.setState({ account }));
  }

It gets called every time props change, even though the fetch promise does not change, not good. I only want it to get called once. when (ps.pending => ps.setteled).
if the promise mapping changes and fetch occurs again, only then call the .then() again.

right now I need to keep track of when (ps.pending => ps.setteled) happens myself which is tedious.
would be really nice to be able to do

connect({
  fetchAccountPs: {
     method: "GET",
     url: "/some/url",
     callback: "onAccountFetched"    // <==  suggestion
  }
)...

and the HOC would call my component exposed onAccountFetched(value) once, using a ref.

what do you think?
is there another existing way i'm missing?

Warning shown when component is unmounted while refetch request is pending

If a user clicks on a button that unmounts the current component while the component's refetch request is pending, the following warning will be shown in the console after the refetch request is complete:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Refetch.connect(PostList) component.

Are we supposed to cancel the refetch request within componentWillUnmount() ? How can we do that?

Incompatible with stateless authentication

I'm using JWT's as my authentication mechanism in my SPA, persisted to window.sessionStorage. When I make calls to my API, I configure the request with an Authorization: Bearer TOKEN header that authorizes the request.

Since API calls in react-refetch are defined outside the context of the component class itself, they cannot pick up changes during runtime to get the current token.

Here's an overview of the flow:

  1. User loads the application on a hard server-request; app initializes in the client, and refetch-enabled components are loaded.

    Refetch configuration on a protected route like ...

    // lib.js
    export const jwt = () => sessionStorage.token;
    export const authHeader = () => {
      if (jwt()) return { 'Authorization': `Bearer ${jwt()}` };
      return {};
    };
    
    // protected_component.js
    connect(() => ({ fetchStuff: { url: '/api/stuff', headers: authHeader() }})(Component);

    ... assign headers: {} since the user starts off logged-out, thus no token is present in window.sessionStorage.

  2. User logs in. Login handler writes the returned, valid token to window.sessionStorage.

    // lib.js
    export const login = ({ token }) => {
      sessionStorage.setItem('token', token);
    };
    
    // login.js
    componentWillReceiveProps(nextProps) {
      if ((nextProps.postLoginResponse || {}).fulfilled) {
        login(nextProps.postLoginResponse.value);
        this.context.router.push({ pathname: '/' });
      }
    }
  3. User accesses protected resource /stuff and refetch fails, because the API request was made with no Authorization header (from Step 1).

    GET http://domain/stuff 403 (Forbidden)

For now, I'm working around the issue by changing:

this.context.router.push({ pathname: '/' });

... to ...

window.location = '/';

But I don't consider that an optimal solution because I have to re-initialize the entire app on successful login, which seems excessive.

Is there any other way around this? Or an alternative approach?

POST action does not trigger the same request

When the first submit attempt failed (rejected), the user re-enter the details and execute upgradePlan again, but there was no HTTP request performed. Because, it's a POST request so I don't expect that it should be cached?!

submit() {
   this.props.upgradePlan(data)
}
...
export default connect(props => ({
  tokenFetch: `/api/v1/organisations/${props.params.organisationId}/payments/token`,
  upgradePlan: data => ({
    upgradePlanResponse: {
      url: `/api/v1/organisations/${props.params.organisationId}/payments/upgrade`,
      method: 'POST',
      body: JSON.stringify({ data })
    }
  })
}))(SubscriptionUpgrade)

Integration with Redux Form

Would be awesome if "lazy fetches" returns a promise, as Redux Form expects a promise to be passed to handleSubmit we'll be able to do things like this:

(PromiseState doesn't help in this case, because it'll be available only after triggering handleSubmit)

import React from 'react';
import { reduxForm } from 'redux-form';
import { connect } from 'react-refetch';
import Panel from '@hnordt/reax-panel';
import PanelBody from '@hnordt/reax-panel-body';
import Form from '@hnordt/reax-form';
import Alert from '@hnordt/reax-alert';
import FormGroup from '@hnordt/reax-form-group';
import Label from '@hnordt/reax-label';
import Input from '@hnordt/reax-input';
import Button from '@hnordt/reax-button';
import Spinner from '@hnordt/reax-spinner';
import { isEmpty } from '@hnordt/reax-validator';

const ProjectForm = ({
  fields: { name },
  submitting,
  error,
  handleSubmit,
  resetForm,
  postProject
}) => (
  <Panel title="Add Project">
    <PanelBody>
      <Form onSubmit={handleSubmit(data => postProject(data).then(resetForm))}>
        {error && <Alert type="danger">{error}</Alert>}
        <FormGroup error={name.touched && name.error}>
          <Label>Name</Label>
          <Input {...name} disabled={submitting} />
        </FormGroup>
        <Button type="primary" submit disabled={submitting}>
          {submitting ? <Spinner /> : 'Save'}
        </Button>
      </Form>
    </PanelBody>
  </Panel>
);

// ES7 decorators will bring a better syntax in the future :)
export default reduxForm(
  {
    form: 'project',
    fields: ['name'],
    validate: ({ name }) => {
      return {
        name: isEmpty(name) && 'Required'
      };
    }
  }
)(connect(() => ({
  postProject: data => ({
    postProjectResponse: {
      url: 'https://httpbin.org/post',
      method: 'POST',
      body: JSON.stringify(data)
    }
  })
}))(ProjectForm));

Identity Requests (value attribute)

Add a value attribute to requests (aka mappings) the return the value in lieu of actually fetching data from url. Requests with value are not allowed to also have a value.

This will support composable transformations, like this (from #21):

connect((props) => ({
  data: {
    url: "/api/data",
    then: (rawValue) => ({ 
      value: rawValue.real_data 
    })
  }
}))(Component)

and will also provide a way to create static PromiseStates, like this (from #19):

connect((props) => ({
    project: `/api/projects/${props.id}`,
    updateProject: (data) => ({
        project: { 
          url: `/api/projects/${props.id}`, 
          method: "PATCH", 
          body: data,
          andThen: () => ({
            projectUpdated: { 
              value: true // some static value of your choice
            }
          })
        }
    })
}))

Working with containers

Hi, I was trying to use react-refetch putting the api calls in a container an passing them to a dump component. The issue is that I am not able to pass custom props like another container method to the dump component. Here the code:

Container:

import React, { Component } from 'react'
import { connect, PromiseState } from 'react-refetch'
import Form from '../components/Form'

export default class Edit extends Component {
  render() {
    const { getSchema, getResume, postResume, deleteResume } = this.props

    const allFetches = PromiseState.all([getSchema, getResume])

    if (allFetches.pending) {
        return <span>loading</span>
      } else if (allFetches.rejected) {
        return <span></span>
        return <span>{allFetches.reason}</span>
      } else if (allFetches.fulfilled) {
      const [schema, resume] = allFetches.value
        return <Form schema={schema} resume={resume} onPost={postResume} onDelete={deleteResume} />
        }
    }
}

export default connect(props => ({
  getSchema: '/api/schema',
  getResume: `/api/resume/${props.routeParams.name}`,
  postResume: resume => ({
    postResumeResponse: {
      url: `/api/resume/${props.routeParams.name}`,
      method: 'POST',
      body: JSON.stringify({ resume })
    }
  }),
}))(Edit)

Component:

import React, { Component } from 'react'

class form extends Component {
    log = (type) => console.log.bind(console, type);

    render() {
           console.log(this.props);
        const { resume, schema, postResume } = this.props

        const log = (type) => console.log.bind(console, type);

        return (
            <Form schema={schema}
            formData={resume}
            onChange={log("changed")}
            onSubmit={postResume}
            onError={log("errors")} />
        )
    }
}

export default form

Rejected promises don't get error messages in IE8

Hi,

I'm not sure if IE8 is supposed to be supported or not, but after polyfilling all of the things this library almost works perfectly.

The only issue I've encountered is that IE8 refuses to accept a message for the error that is thrown when rejecting promises because of the second id parameter. If you delete the id then everything seems to work fine.

As far as I can tell Error isn't supposed to have a second argument anyway so I'm not sure what the id is for, but it could be handled with a custom error type that does take a second argument - this could also be useful to support passing more than just a message on a server error.

Doc example not compiling

I've been hacking at this for a while now, but for some reason can't get the example from the docs below to compile:

connect(({ name }) => ({
   foosFetch: '/foos',
   createFoo: name => {
     method: 'POST',
     url: '/foos',
     andThen: () => {
       foosFetch: {
         url: '/foos',
         refreshing: true
       }
     }
   }
 }))

The error message given is:

Module build failed: SyntaxError: /Users/Joe/Documents/demo/client/app/bundles/demo/startup/Root.jsx: Unexpected token (108:8)
18:30:26 client.1 |   106 |    createFoo: name => {
18:30:26 client.1 |   107 |      method: 'POST',
18:30:26 client.1 | > 108 |      url: '/foos',
18:30:26 client.1 |       |         ^
18:30:26 client.1 |   109 |      andThen: () => {
18:30:26 client.1 |   110 |        foosFetch: {
18:30:26 client.1 |   111 |          url: '/foos',

In my own code, I've been trying to make it possible to delete a record and then refresh the data , and it seems as though the example above would allow me to do that, but it doesn't seem to compile. The other snippets given do compile fine

I've tried updating all of my dependencies,restarting my server and a whole bunch of different combinations, but I've only been able to get things to work by wrapping foosFetch and createFoo in parenthesis. This doesn't have the same functionality though and prevents me from modifying the "name" props, which prevents me from refetching automatically.

My work around so far has been to fetch data using refetch but then in my root react component I have to handle all of the logic for updating there:
ie.

  _destroy(id) {
    this.props.destroy(id);
    this.props.refresh();
  }

Feature request: Transform functions

(Split from #17)
What do you think about adding some convenience features?

Data transform functions

For cases where the data returned is inconvenient to work with directly. Maybe we can reuse then, but I think it's not possible now.

connect((props) => ({
  data: {
    url: "/api/data",
    transform: ((rawValue) => rawValue.real_data)
  }
}))(Component)

Issues in Safari on iOS

It looks like there are a couple of bugs in iOS. The first one is that a polyfill is required for Object.assign. Secondly, the PromiseState fails to resolve in iOS. I'm using the latest release candidate.

postsFetch is undefined

Not sure if it's something I'm doing stupidly wrong this evening or something's not right...

In my code I have react-refetch:

import { connect } from 'react-refetch'

I have my component:

export default class PostFeed extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    const { postsFetch } = this.props

    if (postsFetch.pending) {
      return <span>Loading Posts...</span>
    } else if (postsFetch.rejected) {
      return <span>Failed to load posts</span>
    } else if (postsFetch.fulfilled) {
      return (
        <Post>
          {postsFetch.value}
          <span>This is a post</span>
        </Post>
      )
    }
  }
}

and I have my refetch connect...

connect((props) => ({
  postsFetch: `https://api.github.com/users/${props.user}/gists`,
}))(PostFeed)

and all I'm getting is that postsFetch is undefined.

Any ideas?

support falsy values for value in mapping?

Hi,

The condition at https://github.com/heroku/react-refetch/blob/master/src/components/connect.js#L51 causes a request like

connect(props => {
  return {
    blahFetch: {
      url: '/some/url'
      then: value => {
        if (value.some.key)
          return '/some/other/url'
        else
          return {value: null}
      }
    }
  }
})(MyComponent)

to be invalid. I understand the need to validate there is a url or value, however, how should I do a request like this? (ie. a request in which you poll a first url, you use the response of that to check whether something exists, if it exists you do the request you really want, otherwise that first request doesn't need a value)

Nuno

Side-effects with the Refetch equivalent of Redux's "action creators"?

Related to the section on Posting + Refreshing Data, I'd like to push a new browser state after an update action. In my app, there is no separate view for an "edit" action: users can click an edit button, and the row reformats to inputs. My problem lies in redirecting back to the list view after the update action completes.

I have it working with the following:

import React, { Component } from 'react';
import { connect } from 'react-refetch';
import { authHeader } from 'lib';

class List extends Component {

  // ...

  componentWillReceiveProps(nextProps) {
    const { fetchPref: nextFetchPref } = nextProps;
    const { fetchPref } = this.props;

    if (fetchPref && nextFetchPref && fetchPref.pending && nextFetchPref.fulfilled) {
      this.context.router.push({ pathname: '/admin/prefs' });
    }
  }

  // ...

  render() {
    // omitting the rest of the JSX for the sake of brevity, but this is actually
    // a table where each row has an edit button that invokes `patchPref`
    // with the `id` for the row and the `data` from user input
    return (
      <a onClick={this.props.patchPref.bind(this, id, data)}>edit</a>
    );
  }
}

export default connect((props) => ({
  fetchPrefs: {
    url: '/api/prefs',
    headers: authHeader(),
  },
  patchPref: (id, data) => ({
    fetchPref: {
      url: `/api/prefs/${id}`,
      method: 'PATCH',
      body: JSON.stringify(data),
      headers: authHeader(),
      andThen: () => ({
        fetchPrefs: {
          url: '/api/prefs',
          headers: authHeader(),
          force: true,
          refreshing: true,
        }
      }),
    }
  }),
}))(List);

As you can see, I've had to do some this.props/nextProps checking in componentWillReceiveProps to support the behavior I'm after.

What I'd _like_ to do is define a then clause on patchPref so that I could invoke it along the lines of:

this.props.patchPref(id, data).then(() => {
  this.context.router.push({ pathname: '/admin/prefs' });
})

The intention being:

Do all the react-refetch stuff defined in connect for patchPref, then do this other thing.

That would allow me to completely delete componentWillReceiveProps.

As the return of this.props.patchPref() is undefined, and as then: and andThen: don't have access to this.context, it doesn't seem like my desired solution is possible currently.

I don't know if such a thing would be possible, or if there is another/cleaner way of accomplishing the same behavior with the library as it is now.

Was hoping to hear y'alls thoughts on this.

Switch to isomorphic-fetch

The module, as it sits, is almost perfect for my use case. However, I need to render components server side too. Would you be open to a PR that replaces whatwg-fetch with a similar, standards compliant polyfill that also works in Node?

Create TodoMVC Example

React Refetch has a lot of example snippets, but not a working complete example app. This is an ask to anyone out there who would like to create an example app based on TodoMVC (http://todomvc.com).

Clicking back button loads JSON representation in Rails

I've just started implementing RR in a Ruby on Rails app and I seem to be running into an issue where if I navigate to another page and then click the back button, the JSON file that was rendered via the connect call is what loads on the page. Has anyone hit this issue before?

In my console, my sequence of commands looks like this:

On page load:

# Loading the template
 | Started GET "/" for ::1 at 2016-02-25 18:31:53 -0500
 | Processing by SurveysController#index as HTML
...
# Loading the JSON data via the connect call
 | Started GET "/" for ::1 at 2016-02-25 18:31:54 -0500
 | Processing by SurveysController#index as JSON

Then if I navigate to another page and click the back button, only the JSON data loads.

My controller looks like:

  # Get all surveys and return them
  # {Surveys: [survey_one,survey_two,...]}
  def index
    surveys = Survey.where(user_id: current_user.id)

    respond_to do |format|
      format.html
      format.json { render :json => { surveys: surveys } }
    end
  end

Could the problem be that I'm using Rails for routing? It seems like the only apps I've seen implementing RR use React-Router instead

Compiled version of react-refetch

It seems like the only way to use react-refetch is by setting up webpack, babel, and the rest of the toolchain. I really like the simplicity of this library for putting together quick proof-of-concepts, for which I don't want to bother about setting up the webpack toolchain.

I couldn't find a single compiled js that I could use. I also didn't manage to create a pure compiled version using webpack. Is there a chance one such file could be included as a release? And potentially even added to cdnjs or so?

Filling data server side instead of on client side

There doesn't seem to be a mention of how one can use this library to fetch data and populate views on the server side. Is it possible to do so with this library ร  la react-resolver? It would be a nice addition for people looking to build completely isomorphic apps.

Question About Refetching

export default connect((props) => {
  const url = '/api/devices';
  return {
    devicesSearch : url,
    refreshDevices : () => ({
      devicesSearch : {
        url,
        refreshing : true,
      },
    }),
  };
})(DevicesList);

I have a question about line 148 on connect.js (https://github.com/heroku/react-refetch/blob/master/src/components/connect.js#L148)

Currently, it checks if the mapping is equal between the previous request and the next one. From my local testing, this causes a mapping to be refetched only once, then that mapping will be equal to the previous mapping on subsequent requests.

In my example above, in the DevicesList component I have a button that allows the user to click and refresh the list to view the latest devices. They can click the button as many times as they want, but it will only make one request currently, then the equality check returns true between previous and next mapping so the subsequent refetches will fail and that seemed counter-intuitive (unless I'm doing something incorrectly).

Should I be adding additional keys to my mapping so that the comparison check returns false? Should I be passing in a comparison check based on something specific?

If not, it seems to me that it would make more sense here to see if the the mapping is still valid and always refetch regardless of equality, but I'm not sure what that would affect.

I created a local branch to set the refreshing flag to false after a request is complete if refreshing was true and in the default equality check I added refreshing to the array of keys to test against for equality, and that works, but it doesn't seem like a good solution since refreshing is an optional key for a refresh mapping. If a user didn't pass that key in they would still encounter the same issue so I wanted to get everyone's thoughts on other solutions.

add static version of PromiseState#_mapFlatMapValue ?

That method is useful when building components that receive a prop that may or may not be a PromiseState.

eg.

const Comp = ({table}) => {
  table = table instanceof PromiseState ? table : PromiseState.resolve(table)
  return (
    <div>
      {table.fulfilled && <span>{table.value.length}</span>}
    <div>
  )
}

(It should probably get a name like PromiseState.ensure(), mapFlatMapValue is kind of cryptic)

Sounds like a useful addition?

then/andThen with empty response body

With the following:

connect((props) => {
  fetchPrefs: '/api/prefs',
  deletePref: (id) => ({
    doDeletePref: {
      url: `/api/prefs/${id}`,
      method: 'DELETE',
      andThen: () => ({
        url: '/api/prefs',
        force: true,
        refreshing: true,
      })
    })
  }),
})(Component)

Invoking deletePref() never calls andThen on doDeletePref.

I've determined this is because my API returns a 204: No Content with an empty response body. If I change the response to be a 200: OK and return an empty JSON object, andThen fires normally and everything works.

I also tried returning a 200: OK with an empty body, and the andThen did _not_ fire.

So my guess is that andThen only fires if the response body is not empty.

Personally, I think andThen should fire if the response was successful, regardless if the response body is present.

NOTE: I encountered the same behavior with then.

RR with Redux

I'm opening this issue to start a discussion on how to use both RR and Redux together.

My first idea is something like:

class Foo extends React.Component {
  componentWillReceiveProps(nextProps) {
    const { dispatch } = this.props; // Injected by Redux
    if (nextProps.fooFetch.fulfilled) { // Injected by RR
      dispatch(updateFoo(nextProps.fooFetch.value)); // updateFoo is an action and we pass PS.value as payload
    }
  }
}

// normal RR/Redux connects...

I don't see any problems with this approach. @gaearon thoughts?

Worth noting: if your app don't need to maintain local state, Redux/Flux is optional (https://github.com/heroku/react-refetch#motivation)

Custom error handling

I'm using a RESTful API that when I get a validation error the following response is thrown:

{ "errors": { "field1": "Field is required", "field2": "Field is required", ... } }

They react-refetch is handling promise reject rejection is by supporting a single error that must be a string. Passing an object will result in having the error message "[object Object]" due to string casting of the response JSON...

We must either have support for custom error handling OR at least get access to to the original response somehow.

Add setVariables-like functionality to refetch, as in Relay

At the moment the connect() is a function of props alone, so there is no way for an object to change what it currently displays (think about a timeline graph component with a timerange selection - when range changes, different data should be loaded).

If we add somehting something like "setVariables()" which is a little similar to doing setState() on the HOC connect, we can achieve this.
see Relay specs:
https://facebook.github.io/relay/docs/api-reference-relay-container.html

what do you think?

Should manual request return promise?

When doing requests from event handlers, I wanted to be notified when request finishes, so that I could show message to the user. Like this:

onSave() {
  this.props.updateData(this.state.data).then(() => flash("Saved"))
}

I'm not sure what value should be passed to the promise though.

Request equality does not consider default request attributes

Requests are compared before defaults are applied, so if one request depends on an implicit default attribute and one explicitly declares the default attribute, they will be considered not equal.

For example (reported in #26), the first deviceMessageSearch has an implicit method : 'GET', but the second deviceMessageSearch has an explicit method : 'GET'. Even though the two are essentially equal, they are considered different requests and fetched again one time on this.props.refreshMessages():

export default connect((props) => {
  const deviceMessageUrl = `${process.env.API_URL}api/users/${props.params.userId}/device-messages`;
  return {
    deviceMessageSearch : deviceMessageUrl,
    refreshMessages : () => ({
      deviceMessageSearch : {
        url : deviceMessageUrl,
        method : 'GET',
        refreshing : true
      },
    }),
  };
})(DeviceMessages)

The fix is probably to break out the defaults from buildRequest() and apply them during request coercion so they are memoized and compared during the equality check.

cc: @jwdotjs

Passthrough meta on all requests

Currently, meta only works if value is also set (i.e. only for identity requests). I'm thinking that a better way would be for meta to work for URL-based requests too and for request and response to be merged into meta. This would allow applications to add arbitrary metadata to any request and make it accessible to the component. I don't have a great use case of that off hand, but I like that it makes identity requests more "normal." The downside I see that meta currently allows any data type, but if we go this route, it would have to be an object. Thoughts?

Static Data not immediately fulfilled?

Maybe I'm misunderstanding something, but I'd assume that static data definitions like the following:

export default connect((props) => ({
  userFetch: { value: { id: 1, name: 'Tigger' }}
})(Component);

... would be available immediately, say, in the initial render:

render() {
  const user = this.props.userFetch.value;
}

However, it seems that on the initial render, this.props.userFetch.pending is true. I can't seem to get access to the static data until componentWillReceiveProps.

Shouldn't the PromiseState for a static data definition be immediately fulfilled?

PromiseState and any other kind of promised props

So I've found a kind of sideways use for the ideas of PromiseState and connect (as a HOC that computes additional async props from your regular props). Components that need to compute props asynchronously derived from the other props need most of the ideas behind react-refetch (the props need to be represented as something that can be fulfilled, rejected, pending; it needs figure out whether to recompute when props change). In a way it's a lower-level primitive on top of which react-refetch is built. Do you think it belongs in react-refetch in any way?

I'm using it like this:

export default withPromisedProps({
  table: {
    dependentProps: ['file'], // every time one of these props changes table is recomputed
    then: ({file}) => promisedFileReader(file).readAsText().then(csvParse)
  }
})(CsvTable)

Not sure if this is relevant to anyone, feel free to close this issue :)

Side Effects After Posting Data

What's the best practice to handle side effects after posting data?

Here is my approach:

export default connect(({ history }) => ({
  saveCondition: condition => ({
    saveConditionResponse: {
      method: 'POST',
      url: '/medical/condition',
      body: JSON.stringify(condition),
      andThen: newCondition => {
        history.push(`/medical/${newCondition.id}`);
        return {};
      }
    }
  })
}))(ConditionFormContainer);

Forms

Hello.

I would like to share a HOC I've made to be used with React Refetch:

https://github.com/hnordt/reax-stateful-form

While it's working and I'm using in production, I would like to hear suggestions from the community to handle more form use cases.

The main idea is that the HOC maps common properties to each field, so when you type <TextInput {...foo} /> you'll end up with <TextInput name={foo.name} value={foo.value} touched={foo.touched} error={foo.error} />.
You'll have also isValid (boolean) and handleSubmit that will return a promise with the mapped values when resolved or the first field with error when rejected.

PS.: I stole most of the ideas from the awesome @erikras's Redux Form.

Custom Request Post-Processing

I really like this library, and I'd like to try it for a data-intensive app. Currently, I use d3's csv method to do this:

// (It's CSV, but GitHub Pages only gzip's JSON at the moment.)
d3.csv("large_dataset.csv", function(error, dat) {
   //work with dat
}

I implemented a version with react-refetch, that looks like this:

let AnalysisRefetch = connect((props) => ({
    fetchedData: `large_dataset.csv`
}))(Analysis)

But when I look into this.props.fetchedData, the promise is rejected with the reason "SyntaxError: Unexpected token ,".

I imagine this is because refetch was built for fetching JSON objects. But can I plug in a custom parser or so on the returned value? Or have access to the raw response, somehow? Using refetch will make things so much easier!

Thanks

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.