Skip to content

Instantly share code, notes, and snippets.

@kbingman
Last active December 23, 2020 21:29
Show Gist options
  • Save kbingman/6a339cb5ea9eacbf262d53b3e2fbcd7e to your computer and use it in GitHub Desktop.
Save kbingman/6a339cb5ea9eacbf262d53b3e2fbcd7e to your computer and use it in GitHub Desktop.
/**
* Fetches a model from the State first, then the API.
* returns a tuple with the data from the API and an updater function that
* updates the server
*/
export const useLens= (
uuid: string
): [Response, SetResponse] => {
// This could be `useSelector` and `useDispatch` if we are using Redux
const [initialData, setData] = useRecoilState(
dataSelector(uuid)
);
// The update function, sends a request to the server and sets the response
const updateAndSetModel = (data: Response) => {
// An API PUT request
updateModel((response: Response) => {
setResponse({ ...spacecraft, data: response });
}, data);
};
// Loads the API data asynchronously
useEffect(() => {
// The actual API GET request
getModel((response: Response) => {
setData(response);
}, uuid);
}, [uuid]);
// Returns the data from our State and an update function that
// synchronizes with the server via API
return [initialData, updateAndSetModel];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment