ソースを参照

Create recipe pages

Tatiana Inama 5 年 前
コミット
eda1ee8f34

+ 32 - 0
next-recipes/pages/recipes/[slug].tsx

@@ -0,0 +1,32 @@
+import { FunctionComponent } from 'react';
+import { useRouter } from 'next/router';
+import { getAllRecipes, getRecipe } from '@/utils/api';
+import { InferGetStaticPropsType } from 'next';
+
+export const getStaticPaths = async () => {
+  const recipes = await getAllRecipes();
+  const paths = recipes.map((recipe) => ({
+    params: { slug: recipe._id }
+  }))
+
+  return { paths, fallback: false };
+}
+
+export const getStaticProps = async ({ params }) => {
+  const recipe = await getRecipe(params.slug);
+  return {
+    props: {
+      recipe,
+    }
+  }
+}
+
+const Recipe = ({ recipe }: InferGetStaticPropsType<typeof getStaticProps>) => {
+  return (
+    <div>
+      <p>Recipe: {recipe.name} </p>
+    </div>
+  )
+};
+
+export default Recipe;

+ 10 - 2
next-recipes/pages/recipes.tsx

@@ -3,10 +3,12 @@ import { GetStaticProps, InferGetStaticPropsType } from "next";
 import { getAllRecipes, getAllTags } from '@/utils/api';
 import Header from '@/components/Layout/Header';
 import Container from '@/components/Layout/Container';
+import { useRouter } from 'next/router';
 
 import { Subtitle } from 'components/Typography';
 import RecipeItem from "components/RecipeItem";
 import { TextInput, ChipGroup, Chip } from "@/components/Forms";
+import { MouseEventHandler } from "react";
 
 
 export const getStaticProps = async () => {
@@ -24,6 +26,12 @@ const Recipes = ({
   recipeList = [],
   tags
 }: InferGetStaticPropsType<typeof getStaticProps>) => {
+  const router = useRouter();
+  const openRecipe: (id: string) => MouseEventHandler<Element> = (id) => (e) => {
+    e.preventDefault();
+    router.push(`/recipes/${id}`);
+  }
+
   return (
     <Layout>
       <Header>
@@ -39,8 +47,8 @@ const Recipes = ({
       </Container>
       <Container>
         <Subtitle>All</Subtitle>
-        {recipeList.map((recipe, index) => (
-          <RecipeItem recipe={recipe} key={index} onClick={() => console.log(recipe.name)} />
+        {recipeList.map((recipe) => (
+          <RecipeItem recipe={recipe} key={recipe._id} onClick={openRecipe(recipe._id)} />
         ))}
       </Container>
     </Layout>

+ 1 - 1
next-recipes/types/recipes.d.ts

@@ -1,5 +1,5 @@
 export type Recipe = {
-  id: string;
+  _id: string;
   name: string;
   summary: string;
   tags: string[];

+ 3 - 0
next-recipes/utils/api.ts

@@ -29,7 +29,10 @@ export const getAllTags = () => mockAPI<Tag[]>(
   ]
 );
 
+export const getRecipe = (id: string) => api<Recipe>(`${process.env.API_RECIPES}/id/${id}/`);
+
 export default {
   getAllRecipes,
   getAllTags,
+  getRecipe,
 };