Fakultas Ilmu Komputer UI

Skip to content
Snippets Groups Projects
Commit 52cf258b authored by Muhammad Zaki's avatar Muhammad Zaki
Browse files

refactor: make seperate hooks for each page data calls

parent c99bc4e6
No related branches found
No related tags found
No related merge requests found
const story = (path) => `https://node-hnapi.herokuapp.com/${path}`;
const user = (path) =>
`https://hacker-news.firebaseio.com/v0/${path}.json`;
export default function fetchAPI(path) {
const url = path.startsWith("user") ? user(path) : story(path);
return fetch(url).then((r) => r.json());
}
\ No newline at end of file
%%raw(`function abortableFetch(request, opts) {
const controller = new AbortController();
const signal = controller.signal;
return {
abort: () => controller.abort(),
ready: fetch(request, { ...opts, signal }),
};
}
const story = (path) => "https://node-hnapi.herokuapp.com/" + path;
const user = (path) => "https://hacker-news.firebaseio.com/v0/" + path + ".json";
function fetchAPI(path) {
const url = path.startsWith("user") ? user(path) : story(path);
const { abort, ready } = abortableFetch(url);
return { abort, ready: ready.then((r) => r.json()) };
}`)
external fetch: string => {"abort": unit => unit, "ready": Js.Promise.t<'data>} = "fetchAPI"
let fetch = fetch
let useStoryData = (id: option<string>) => {
let (story, setStory) = React.useState((_): option<Story.t> => None)
React.useEffect1(() => {
let abortableFetch = fetch(j`item/$id`)
if id->Belt.Option.isSome {
abortableFetch["ready"]
->Promise.then(fetchedStory => setStory(_ => Some(fetchedStory))->Promise.resolve)
->ignore
}
Some(abortableFetch["abort"])
}, [id])
story
}
let useStoriesData = (type_: string, page: int) => {
let (stories, setStories) = React.useState((_): array<Story.t> => [])
React.useEffect2(() => {
let abortableFetch = fetch(j`$type_?page=$page`)
abortableFetch["ready"]
->Promise.then(fetchedStories => setStories(_ => fetchedStories)->Promise.resolve)
->ignore
Some(abortableFetch["abort"])
}, (type_, page))
stories
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment