Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

apply swr for list page #34

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"react": "17.0.1",
"react-dom": "17.0.1",
"react-hook-form": "^7.12.0",
"styled-components": "^5.3.0"
"styled-components": "^5.3.0",
"swr": "^0.5.6"
},
"devDependencies": {
"@types/firebase": "^3.2.1",
Expand Down
15 changes: 0 additions & 15 deletions src/firestore/news/retrieveNewsById.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,4 @@ export const RetrieveNewsById = async (id: string): Promise<News> => {
description: doc.data()?.description,
} as News;

// await docRef.get().then((doc) => {
// if (doc.exists) {
// // news.id = doc.id;
// // news.title = doc.data()?.title;
// // news.description = doc.data()?.description;
// return doc;
// } else {
// // doc.data() will be undefined in this case
// console.warn("No such document!");
// return null;
// }
// }).catch((error) => {
// console.warn("Error getting document:", error);
// return null;
// });
};
33 changes: 22 additions & 11 deletions src/pages/admin/news/form/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,33 @@ import NewsFormTemplate from "../../../../components/templates/admin/news/form";
import { GetServerSideProps } from "next";
import { InferGetServerSidePropsType } from "next";
import { RetrieveNewsById } from "../../../../firestore/news/retrieveNewsById";
import { useRetrieveNewsDataById } from "../../../hooks/useRetrieveNewsDataById";
import { useRouter } from 'next/router';

function Form({
news,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
function Form() {
const router = useRouter()

const idNews:string = router.query.id as string;

const { news, isError, isLoading} = useRetrieveNewsDataById(idNews);


if (isError) return <div>failed to load</div>
if (isLoading) return <div>loading...</div>

console.log(news);
return <NewsFormTemplate news={news} />;
}

export const getServerSideProps: GetServerSideProps = async (context) => {
const idNews: string = context.query.id as string;
var news: News = { id: "", title: "", description: "" };
// export const getServerSideProps: GetServerSideProps = async (context) => {
// const idNews: string = context.query.id as string;
// var news: News = { id: "", title: "", description: "" };

news = await RetrieveNewsById(idNews);
// news = await RetrieveNewsById(idNews);

return {
props: { news }, // will be passed to the page component as props
};
};
// return {
// props: { news }, // will be passed to the page component as props
// };
// };

export default Form;
47 changes: 20 additions & 27 deletions src/pages/admin/news/list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,39 +9,32 @@ import { GetStaticProps, GetStaticPropsContext } from "next";
import { InferGetStaticPropsType } from "next";
import { News } from "../../../models/news";
import { RetrieveNews } from "../../../firestore/news/retrieveNews";
import { GetServerSideProps } from "next";
import { InferGetServerSidePropsType } from "next";
// import { GetServerSideProps } from "next";
// import { InferGetServerSidePropsType } from "next";
import "firebase/storage";
import { useNewListData } from "../../hooks/useNewListData";

function List({
newsList,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
// // Create a root reference
// var storageRef = firebase.storage().ref();
// let reader = new FileReader();
function List() {

// ;
// // Create a reference to 'mountains.jpg'
// var mountainsRef = storageRef.child('/photo1.jpg');
// mountainsRef.put(reader.readAsText('/photo1.jpg')).then((snapshot) => {
// console.log('Uploaded a blob or file!');
// });
const { newsList, isError, isLoading} = useNewListData();

if (isError) return <div>failed to load</div>
if (isLoading) return <div>loading...</div>

return <NewsListTemplate newsList={newsList} />;
}

export default List;

export const getServerSideProps: GetServerSideProps = async () => {
var newsList: News[] = [];
// await the promise
newsList = await RetrieveNews();
// export const getServerSideProps: GetServerSideProps = async () => {
// var newsList: News[] = [];
// // await the promise
// newsList = await RetrieveNews();

// By returning { props: { posts } }, the Blog component
// will receive `posts` as a prop at build time
return {
props: {
newsList,
},
};
};
// // By returning { props: { posts } }, the Blog component
// // will receive `posts` as a prop at build time
// return {
// props: {
// newsList,
// },
// };
// };
16 changes: 16 additions & 0 deletions src/pages/hooks/useNewListData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import "firebase/firestore";
import { News } from "../../models/news";
import useSWR from 'swr';
import { RetrieveNews } from "../../firestore/news/retrieveNews";

export function useNewListData() {

Choose a reason for hiding this comment

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

@duoctvd
Thêm kiểu trả về cho function

interface UseNewListData {
  xxxx
}
export function useNewListData(): UseNewListData {

const { data, error } = useSWR("useNewListData", async () => {
return await RetrieveNews();
});

return {
newsList: data as News[],
isError: !!error,
isLoading: !data && !error,
};
}
17 changes: 17 additions & 0 deletions src/pages/hooks/useRetrieveNewsDataById.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import "firebase/firestore";
import { News } from "../../models/news";
import useSWR from 'swr';
import { RetrieveNewsById } from "../../firestore/news/retrieveNewsById";

export function useRetrieveNewsDataById(idNews:string) {

Choose a reason for hiding this comment

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

@duoctvd
Tương tự phía trên, thêm kiểu trả về cho function.
Đổi tên idNews => newsId


const { data, error } = useSWR("useRetrieveNewsDataById", async () => {
return await RetrieveNewsById(idNews);

Choose a reason for hiding this comment

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

@duoctvd
Cách truyền id vào như vậy đúng rồi.
Thường thì mấy file template (.tsx) sẽ viết hoa chữ đầu còn function (.ts) thì viết chữ đầu bình thường nha e.
RetrieveNewsById => retrieveNewsById

Copy link
Owner Author

Choose a reason for hiding this comment

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

@duoctvd
Cách truyền id vào như vậy đúng rồi.
Thường thì mấy file template (.tsx) sẽ viết hoa chữ đầu còn function (.ts) thì viết chữ đầu bình thường nha e.
RetrieveNewsById => retrieveNewsById

@bit-thuynt: Em đang dùng thế này để truyền newsId qua hooks, em đang cảm thấy nó k đc truyền qua mỗi lần request (vì còn còn dùng trong getServerSideProps), nên lúc thì nó qua đc data lúc thì nó là undifie
https://gyazo.com/f594699833b6e16bec1a73ad07de83fd

Choose a reason for hiding this comment

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

@duoctvd
Tại router nó là bất đồng bộ nên news id lấy từ router cũng sẽ bất đồng bộ.
Vấn đề này thì xem sẽ thêm check bên trong useSWR
https://swr.vercel.app/docs/conditional-fetching#conditional

Khi nào news id có giá trị thì mới gọi get.

const { data, error } = useSWR( newsId ? "useRetrieveNewsDataById" : null, async () => {

});

return {
news: data as News,
isError: !!error,
isLoading: !data && !error,
};
}
12 changes: 12 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1361,6 +1361,11 @@ depd@~1.1.2:
resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9"
integrity sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=

dequal@2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.2.tgz#85ca22025e3a87e65ef75a7a437b35284a7e319d"
integrity sha512-q9K8BlJVxK7hQYqa6XISGmBZbtQQWVXSrRrWreHC94rMt1QL/Impruc+7p2CYSYuVIUr+YCt6hjrs1kkdJRTug==

des.js@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/des.js/-/des.js-1.0.1.tgz#5382142e1bdc53f85d86d53e5f4aa7deb91e0843"
Expand Down Expand Up @@ -3601,6 +3606,13 @@ supports-color@^8.0.0:
dependencies:
has-flag "^4.0.0"

swr@^0.5.6:
version "0.5.6"
resolved "https://registry.yarnpkg.com/swr/-/swr-0.5.6.tgz#70bfe9bc9d7ac49a064be4a0f4acf57982e55a31"
integrity sha512-Bmx3L4geMZjYT5S2Z6EE6/5Cx6v1Ka0LhqZKq8d6WL2eu9y6gHWz3dUzfIK/ymZVHVfwT/EweFXiYGgfifei3w==
dependencies:
dequal "2.0.2"

table@^6.0.9:
version "6.7.1"
resolved "https://registry.yarnpkg.com/table/-/table-6.7.1.tgz#ee05592b7143831a8c94f3cee6aae4c1ccef33e2"
Expand Down