Skip to content

Commit

Permalink
add useAPI
Browse files Browse the repository at this point in the history
  • Loading branch information
olmobrutall committed Feb 20, 2019
1 parent e42d0bf commit 9ae1966
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Signum.React/Scripts/Services.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ModelState } from './Signum.Entities'
import { GraphExplorer } from './Reflection'
import * as React from 'react'

export interface AjaxOptions {
url: string;
Expand Down Expand Up @@ -383,3 +384,24 @@ export class AbortableRequest<Q, A> {
}) as Promise<A>;
}
}


export function useAPI<T>(defaultValue: T, key: ReadonlyArray<any> | undefined, makeCall: (signal: AbortSignal) => Promise<T>): T {

const [data, updateData] = React.useState<T>(defaultValue)

React.useEffect(() => {
var abortController = new AbortController();

makeCall(abortController.signal)
.then(result => updateData(result))
.done();

return () => {
abortController.abort();
}
}, key);

return data;

}

1 comment on commit 9ae1966

@olmobrutall
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UseAPI (React Hooks!)

After the pleasure of updating the typescript type definitions (irony), this commit contains the first custom react hook, aimed to simplify doing ajax calls in functional react components.

In order to see how awesome it is, look at this example code:

signumsoftware/southwind@4783afa?diff=split

(The code in Southwind is not merged to master till jquense/react-widgets#917 is accepted)

Why it is awesome

  • For most react components you don't need a class, just a function.
  • Instead of having code spread in componentWillMount, componentWillReceiveProps and loadData, the useAPI takes care of everything.
  • The abstraction is also taking care of aborting the query when the componentWilUnmount! No more warnings when changing the state of a dead component.
  • Using parameter deconstruction, you don't need to do this.props.ctx, just ctx.
  • While this.... "local variables with memory" are strange at the beginning, the idea that props are parameters and state local variables makes React very intuitive. Components are just functions now!.
  • Because handleViewClick is now an inner function, you don't need a lambda and this makes no problems.

image

Please sign in to comment.