Skip to content

Commit 82c83f1

Browse files
committed
feat(graphql): add tasks-list page with base fetching
https://github.com/martis-git/learn-frontend/issues/279
1 parent 4055f7e commit 82c83f1

File tree

6 files changed

+56
-2
lines changed

6 files changed

+56
-2
lines changed

examples/graphql/src/models.d.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
declare type Task = {
2+
userId: number,
3+
id: number,
4+
title: string,
5+
completed: boolean;
6+
}

examples/graphql/src/pages/tasks-list/index.tsx

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,26 @@
11
import React from 'react'
2+
import { useFetch } from "shared/hooks";
23

34
const TasksList = () => {
5+
const { data, error, loading } = useFetch<Task[]>("");
6+
if (error) alert(error);
7+
48
return (
5-
<div>
6-
page:TasksList
9+
<div className="page page-tasks-list">
10+
<div className="page-title">
11+
Tasks List
12+
</div>
13+
<div className="page-content">
14+
{loading && "Loading..."}
15+
<ul>
16+
{data?.map(({ id, title }) => (
17+
<li>{id}: {title}</li>
18+
))}
19+
{data?.length === 0 && (
20+
<li>There are not tasks found</li>
21+
)}
22+
</ul>
23+
</div>
724
</div>
825
)
926
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
/// <reference types="react-scripts" />
2+
/// <reference types="./models" />
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// FIXME: move to env
2+
export const API_DOMAIN = "https://jsonplaceholder.typicode.com/todos";
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { default as useFetch } from "./use-fetch";
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { useState, useEffect } from "react";
2+
import { API_DOMAIN } from "shared/get-env";
3+
4+
const useFetch = <T = any>(url: string, baseUrl = API_DOMAIN) => {
5+
const [loading, setLoading] = useState<boolean>(false);
6+
const [data, setData] = useState<T | null>(null);
7+
const [error, setError] = useState(null);
8+
9+
useEffect(() => {
10+
setLoading(true);
11+
fetch(`${baseUrl}/${url}`)
12+
.then((r) => r.json())
13+
.then((r: T) => {
14+
setData(r);
15+
setLoading(false);
16+
setError(null);
17+
})
18+
.catch((err) => {
19+
setData(null);
20+
setLoading(false);
21+
setError(err);
22+
})
23+
}, [baseUrl, url]);
24+
25+
return { loading, data, error };
26+
}
27+
export default useFetch;

0 commit comments

Comments
 (0)