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

add task solution #2678

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
12 changes: 10 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
import { useState } from 'react';
import './App.scss';
import { MoviesList } from './components/MoviesList';
import { NewMovie } from './components/NewMovie';
import { Movie } from './types/Movie';
import moviesFromServer from './api/movies.json';

export const App = () => {
const [movies, setMovies] = useState<Movie[]>(moviesFromServer);

const handleAddMovie = (newMovie: Movie) => {
setMovies(prevMovies => [...prevMovies, newMovie]);
};

return (
<div className="page">
<div className="page-content">
<MoviesList movies={moviesFromServer} />
<MoviesList movies={movies} />
</div>
<div className="sidebar">
<NewMovie /* onAdd={(movie) => {}} */ />
<NewMovie onAdd={handleAddMovie} />
</div>
</div>
);
Expand Down
102 changes: 91 additions & 11 deletions src/components/NewMovie/NewMovie.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,117 @@
import { useState } from 'react';
import { TextField } from '../TextField';
import { Movie } from '../../types/Movie';

export const NewMovie = () => {
// Increase the count after successful form submission
// to reset touched status of all the `Field`s
const [count] = useState(0);
type Props = {
onAdd: (movie: Movie) => void;
};

const urlPattern =
// eslint-disable-next-line
/^((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www\.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@,.\w_]*)#?(?:[,.!/\\\w]*))?)$/;

const initialFormData = {
title: '',
description: '',
imgUrl: '',
imdbUrl: '',
imdbId: '',
};

export const NewMovie: React.FC<Props> = ({ onAdd }) => {
const [count, setCount] = useState(0);
const [formData, setFormData] = useState<Movie>(initialFormData);
deelray marked this conversation as resolved.
Show resolved Hide resolved

const { title, description, imgUrl, imdbUrl, imdbId } = formData;

const validateUrl = (value: string) => {
return !urlPattern.test(value) ? 'Please enter a valid URL' : null;
};

const isFormValid =
title.trim() &&
validateUrl(imgUrl) === null &&
validateUrl(imdbUrl) === null &&
imdbId.trim();

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;

setFormData(prevData => ({ ...prevData, [name]: value }));
};

const clearForm = () => {
setFormData(initialFormData);
};

const handleSubmit = (event: React.FormEvent) => {
event.preventDefault();

const trimmedData = Object.keys(formData).reduce((acc, key) => {
const typedKey = key as keyof Movie;

return { ...acc, [typedKey]: formData[typedKey].trim() };
}, {} as Movie);

onAdd(trimmedData);

setCount(prevCount => prevCount + 1);

clearForm();
};

return (
<form className="NewMovie" key={count}>
<form className="NewMovie" key={count} onSubmit={handleSubmit}>
<h2 className="title">Add a movie</h2>

<TextField
name="title"
label="Title"
value=""
onChange={() => {}}
value={title}
onChange={handleChange}
required
/>

<TextField name="description" label="Description" value="" />
<TextField
name="description"
label="Description"
value={description}
onChange={handleChange}
/>

<TextField name="imgUrl" label="Image URL" value="" />
<TextField
name="imgUrl"
label="Image URL"
value={imgUrl}
onChange={handleChange}
validate={validateUrl}
deelray marked this conversation as resolved.
Show resolved Hide resolved
required
/>

<TextField name="imdbUrl" label="Imdb URL" value="" />
<TextField
name="imdbUrl"
label="Imdb URL"
value={imdbUrl}
onChange={handleChange}
validate={validateUrl}
deelray marked this conversation as resolved.
Show resolved Hide resolved
required
/>

<TextField name="imdbId" label="Imdb ID" value="" />
<TextField
name="imdbId"
label="Imdb ID"
value={imdbId}
onChange={handleChange}
required
/>

<div className="field is-grouped">
<div className="control">
<button
type="submit"
data-cy="submit-button"
className="button is-link"
disabled={!isFormValid}
>
Add
</button>
Expand Down
17 changes: 12 additions & 5 deletions src/components/TextField/TextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ type Props = {
label?: string;
placeholder?: string;
required?: boolean;
onChange?: (newValue: string) => void;
onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
validate?: (value: string) => string | null;
};

function getRandomDigits() {
Expand All @@ -21,13 +22,18 @@ export const TextField: React.FC<Props> = ({
placeholder = `Enter ${label}`,
required = false,
onChange = () => {},
validate = () => null,
}) => {
// generate a unique id once on component load
const [id] = useState(() => `${name}-${getRandomDigits()}`);

// To show errors only if the field was touched (onBlur)
const [touched, setTouched] = useState(false);
const hasError = touched && required && !value;

const requiredError =
required && !value.trim() ? `${label} is required` : null;
const customError = validate(value);
const error = requiredError || customError;

return (
<div className="field">
Expand All @@ -41,16 +47,17 @@ export const TextField: React.FC<Props> = ({
id={id}
data-cy={`movie-${name}`}
className={classNames('input', {
'is-danger': hasError,
'is-danger': touched && error,
})}
placeholder={placeholder}
name={name}
value={value}
onChange={event => onChange(event.target.value)}
onChange={onChange}
onBlur={() => setTouched(true)}
/>
</div>

{hasError && <p className="help is-danger">{`${label} is required`}</p>}
{touched && error && <p className="help is-danger">{error}</p>}
</div>
);
};
Loading