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

Movie creation form + validation #15

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
"@tanstack/react-query-devtools": "^5.0.0-alpha.91",
"axios": "^1.7.2",
"cors": "^2.8.5",
"formik": "^2.4.6",
"next": "14.2.4",
"react": "^18",
"react-dom": "^18"
"react-dom": "^18",
"yup": "^1.4.0"
},
"devDependencies": {
"eslint": "^8",
Expand Down
39 changes: 39 additions & 0 deletions src/app/containers/create-movie/createMovieForm.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Formik, Form } from "formik"
import {FormField} from "./formField"
import {DynamicFormField} from "./dynamicFormField"
import * as yup from "yup"

const initialValues = {
id: '',
title: '',
description: '',
genres: [{ id: '', name: '' }],
video_source: '',
cast: [{ role: '', crew: [{ id: '', name: '' }] }],
};

const validationSchema = yup.object().shape({
id: yup.number().required(),
title: yup.string().required(),
description: yup.string().required(),
video_source: yup.string().url().required()
})
export const CreateMovieForm = ({mutate}) => (
<Formik initialValues={initialValues} validationSchema={validationSchema}>
{({ values, errors }) => (
<Form className="w-1/2 flex flex-col items-center mt-8">
<FormField label="Movie ID" name="id" type="text" error={errors.id}/>
<FormField label="Movie Title" name="title" type="text" error={errors.title}/>
<FormField label="Movie Description" name="description" type="text" error={errors.description}/>
<FormField label="Movie Video Source" name="video_source" type="text" error={errors.video_source}/>
<DynamicFormField name="genres" label="Genre" fields={[['ID', 'id'], ['Name', 'name']]} values={values}/>
<DynamicFormField name="cast" label="Cast" fields={[['Role', 'role']]}
values={values}
nestedFields={[{ name: 'crew', label: 'Crew', fields: [['ID', 'id'], ['Name', 'name']] }]}/>
<button className="w-1/2 px-4 py-2 bg-[#0B0C10] text-white rounded" type="submit" onClick={() => mutate(values)}>
Create movie
</button>
</Form>
)}
</Formik>
)
52 changes: 52 additions & 0 deletions src/app/containers/create-movie/dynamicFormField.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { FieldArray } from 'formik';
import {FormField} from './formField';

export const DynamicFormField = ({ name, label, fields, values, nestedFields, nestedIndex}) => (
<>
<FieldArray name={name}>
{({ remove, push }) => (
<div className="w-full mt-4 py-5">
<h3 className="text-xl text-white font-semibold mb-2">{label}</h3>
{(values[name]||[]).map((_item, index) => (
<div key={`${index}.${nestedIndex}`} className="w-full mb-4 text-black flex items-center space-x-2">
{fields.map(([fieldLabel, fieldName]) => (
<div key={`${name}.${index}.${fieldName}.${nestedIndex}`} className="flex-grow">
<FormField
key={`${name}.${index}.${fieldName}.${nestedIndex}`}
label={fieldLabel}
name={`${name}.${index}.${fieldName}.${nestedIndex}`}
type="text"
/>
</div>
))}

{nestedFields && nestedFields.map((nestedField,nestedIndex) => (
<div key={`${name}.${index}.${nestedIndex}.${nestedField.name}`} className="w-full">
<DynamicFormField
key={`${name}.${index}.${nestedIndex}`}
nestedIndex={`${index}.${nestedIndex}`}
name={nestedField.name}
label={nestedField.label}
fields={nestedField.fields}
values={values}
/>
</div>
))}
<button type="button" className="px-3 py-5 bg-[#66FCF1] text-white rounded" onClick={() => remove(index)}>X</button>
</div>
))}
<div className="flex justify-end">
<button type="button" className="bg-[#45A29E] text-white rounded px-4 py-2" onClick={() => push(fields.reduce((acc, [fieldLabel, fieldName]) => ({ ...acc, [fieldName]: '' }), {}))}>
Add {label}
</button>
</div>
</div>

)}
</FieldArray>

</>


);

23 changes: 23 additions & 0 deletions src/app/containers/create-movie/formField.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Field } from "formik"

export const FormField = ({ label, placeholder, name, type, error }) => {
const nameParts = name.split('.');

let transformedName = nameParts[1] != undefined?`${nameParts[0]}[${nameParts[1]}].${nameParts[2]}`:`${nameParts[0]}`;
if(nameParts[0] == "crew"){
Copy link
Owner

Choose a reason for hiding this comment

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

Instead of edge casing a component that can be reusable to handle "crew", we could leave the FormField as a template and create a CrewFormField that would handle the transformed name for the crew. Also, why do we need such a long name for the input name?

transformedName = `cast[${nameParts[3]}].crew[${nameParts[1]}].${nameParts[2]}`;
}

return (
<div className="w-1/2 mb-4">
<label className="text-white font-medium mb-1">{label}</label>
<Field
placeholder={placeholder}
name={transformedName}
type={type}
className="field w-full p-2 border border-gray-300 rounded"
/>
{error && <div className="field-error text-red-500 mt-1">{error}</div>}
</div>
);
};
34 changes: 26 additions & 8 deletions src/app/containers/create-movie/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,20 @@

import { useMutation } from "@tanstack/react-query"
import axios from "axios"
import { CreateMovieForm } from "./createMovieForm"

const createMovie = async () => {
const response = await axios.post('/api/movies', {id: 7, name: "Dune" })

const createMovie = async (values) => {
console.log(values)
Copy link
Owner

Choose a reason for hiding this comment

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

We should remove this console log

const movie = {
id: parseInt(values.id),
title: values.title,
description: values.description,
genres: values.genres,
video_source: values.video_source,
cast: [values.cast],
};
const response = await axios.post('/api/movies', movie)

return response.data
}
Expand All @@ -16,13 +27,20 @@ export const CreateMovie = () => {
})

return <>
<div className="flex items-center justify-center">
<CreateMovieForm mutate={mutate} />
</div>

{isError && <div className="text-red-600">{error.message}</div>}
<button onClick={() => mutate()}>Create movie</button>
{isSuccess && <div>
Newly created movie
<p>This is id: {data.id}</p>
<p>This is movie name: {data.name}</p>

{isSuccess && <div className="py-10 text-white flex flex-col items-center bg-[#45A29E] opacity-90">
<h2 className="font-bold text-3xl py-5">Newly created movie!</h2>
<p>This is the movie id: {data.id}</p>
<p>This is the movie name: {data.title}</p>
<p>This is the movie description: {data.description}</p>
<p>This is the movie video_source: {data.video_source}</p>
</div>}
</>

}
}

14 changes: 9 additions & 5 deletions src/app/create-movie/page.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { CreateMovie } from "../containers/create-movie"
import { CreateMovie } from "../containers/create-movie";

const CreateMoviePage = () => {
return <div>
Create Movie
<CreateMovie />
return (
<div>
<div className="flex flex-col items-center w-full">
<h1 className="text-white text-center mt-8 mb-4 text-5xl">Create Movie</h1>
</div>
<CreateMovie />
</div>
);
}

export default CreateMoviePage
export default CreateMoviePage;
2 changes: 1 addition & 1 deletion src/app/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function RootLayout({ children }) {
return (
<html lang="en" className="h-full">
<body
className={`${inter.className} bg-[url('../assets/background.jpg')] h-full bg-center bg-cover bg-no-repeat`}
className={`${inter.className} bg-[url('../assets/background.jpg')] h-full bg-center bg-cover bg-repeat-y`}
>
<Providers>
<Header />
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/movies.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const handler = (req, res) => {
const data = JSON.parse(fs.readFileSync(dataFilePath, "utf8"));

const alreadyExists = data.some(
(movie) => movie.id === newData.id || movie.name === newData.name,
(movie) => movie.id === newData.id || movie.title === newData.title,
);

if (alreadyExists) {
Expand Down
58 changes: 52 additions & 6 deletions src/pages/api/movies.json
Original file line number Diff line number Diff line change
@@ -1,26 +1,72 @@
[
{
"id": 1,
"name": "Interstellar"
"title": "Interstellar"
},
{
"id": 2,
"name": "Avatar"
"title": "Avatar"
},
{
"id": 3,
"name": "Lord of the Rings"
"title": "Lord of the Rings"
},
{
"id": 4,
"name": "Titanic"
"title": "Titanic"
},
{
"id": 5,
"name": "Hobbit"
"title": "Hobbit"
},
{
"id": 7,
"name": "Dune"
"title": "Dune"
},
{
"id": "10",
"title": "The Pianist",
"description": "From 2002",
"genres": [
{
"id": "1",
"name": "War"
},
{
"id": "2",
"name": "Drama"
}
],
"video_source": "https://www.youtube.com/watch?v=BFwGqLa_oAo",
"cast": [
[
{
"role": "Role1",
"crew": [
{
"id": "1",
"name": "Crew1"
},
{
"id": "2",
"name": "Crew2"
}
]
},
{
"role": "Role2",
"crew": [
{
"id": "3",
"name": "Crew3"
},
{
"id": "4",
"name": "Crew4"
}
]
}
]
]
}
]
Loading