ql
88 строк · 3.2 Кб
1import React, { useEffect } from 'react';
2import { useSelector, useDispatch } from 'react-redux';
3import { RootState, AppDispatch } from '../../store/store';
4import { setQuery, setCurrentPage } from '../../store/features/searchSlice';
5import { useLazyQuery} from '@apollo/client';
6import { Link } from 'react-router-dom';
7import {GET_USER_REPOS} from "../../resurce/get_user_repos.tsx";
8import {SEARCH_REPOS} from "../../resurce/search_repos.tsx";
9import styles from './Home.module.scss';
10
11interface RepositoryNode {
12name: string;
13owner: {
14login: string;
15};
16stargazers: {
17totalCount: number;
18};
19updatedAt: string;
20url: string;
21}
22
23const Home: React.FC = () => {
24const query = useSelector((state: RootState) => state.search.query);
25const currentPage = useSelector((state: RootState) => state.search.currentPage);
26const dispatch = useDispatch<AppDispatch>();
27
28const [searchRepositories, { data: searchData, loading: searchLoading }] = useLazyQuery(SEARCH_REPOS);
29const [getUserRepositories, { data: userData, loading: userLoading }] = useLazyQuery(GET_USER_REPOS);
30
31useEffect(() => {
32const variables = {
33first: 10,
34after: currentPage > 1 ? (query ? searchData?.search.pageInfo.endCursor : userData?.viewer.repositories.pageInfo.endCursor) : null
35};
36
37if (query) {
38searchRepositories({ variables: { ...variables, query } });
39} else {
40getUserRepositories({ variables });
41}
42}, [query, currentPage]);
43
44const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
45dispatch(setQuery(e.target.value));
46dispatch(setCurrentPage(1));
47};
48
49const handlePageChange = (page: number) => {
50dispatch(setCurrentPage(page));
51};
52
53const repositories = query ? searchData?.search.edges : userData?.viewer.repositories.edges;
54
55return (
56<div className={styles.container}>
57<input
58type="text"
59className={styles.input}
60value={query}
61onChange={handleSearchChange}
62placeholder="Search repositories"
63/>
64{(searchLoading || userLoading) && <p>Loading...</p>}
65<ul className={styles.box}>
66{repositories?.map(({ node }: { node: RepositoryNode }) => (
67<li key={node.name} className={styles.item}>
68<p>{node.owner.login}</p>
69<Link to={`/repository/${node.owner.login}/${node.name}`}>{node.name}</Link> - {node.stargazers.totalCount} stars - {new Date(node.updatedAt).toLocaleDateString()} - <a href={node.url} target="_blank" rel="noopener noreferrer">GitHub</a>
70</li>
71))}
72</ul>
73<div className={styles.btn}>
74{[...Array(10)].map((_, i) => (
75<button
76key={`page-${i}`}
77onClick={() => handlePageChange(i + 1)}
78style={{ fontWeight: currentPage === i + 1 ? 'bold' : 'normal' }}
79>
80{i + 1}
81</button>
82))}
83</div>
84</div>
85);
86};
87
88export default Home;
89