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

solution #2091

Open
wants to merge 4 commits 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
14 changes: 12 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
import { useState } from 'react';
import './App.scss';
import { MoviesList } from './components/MoviesList';
import { NewMovie } from './components/NewMovie';
import moviesFromServer from './api/movies.json';
import { Movie } from './types/Movie';

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

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

return (
<div className="page">
<div className="page-content">
<MoviesList movies={moviesFromServer} />
<MoviesList movies={movies} />
</div>
<div className="sidebar">
<NewMovie /* onAdd={(movie) => {}} */ />
<NewMovie
onAdd={addMovies}
/>
</div>
</div>
);
Expand Down
100 changes: 87 additions & 13 deletions src/components/NewMovie/NewMovie.tsx
Original file line number Diff line number Diff line change
@@ -1,53 +1,127 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import cn from 'classnames';
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);
// eslint-disable-next-line max-len
const pattern = /^((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www\.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@,.\w_]*)#?(?:[,.!/\\\w]*))?)$/;

type Props = {
onAdd: (post: Movie) => void;
};

export const NewMovie: React.FC<Props> = ({ onAdd }) => {
const [count, setCount] = useState(0);
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [imgUrl, setImgUrl] = useState('');
const [imdbUrl, setImdbUrl] = useState('');
const [imdbId, setImdbId] = useState('');
const [isFormValid, setIsFormValid] = useState(false);

const reset = () => {
setCount(0);
setTitle('');
setDescription('');
setImgUrl('');
setImdbUrl('');
setImdbId('');
setIsFormValid(false);
};

const correctImgUrl = pattern.test(imgUrl);
const correctimdbUrl = pattern.test(imdbUrl);

const isValid
= !!title && pattern.test(imgUrl) && pattern.test(imdbUrl) && !!imdbId;

const handleInputChange = (
setter: React.Dispatch<React.SetStateAction<string>>, value: string,
) => {
setter(value);

setIsFormValid(isFormValid);
};

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

const newMovie: Movie = {
title,
description,
imgUrl,
imdbUrl,
imdbId,
};

onAdd(newMovie);
setCount(count + 1);
};

useEffect(() => {
if (count > 0) {
reset();
}
}, [count]);

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={(value) => handleInputChange(setTitle, value)}
required
/>

<TextField
name="description"
label="Description"
value=""
value={description}
onChange={(value) => handleInputChange(setDescription, value)}
/>

<TextField
name="imgUrl"
label="Image URL"
value=""
value={imgUrl}
onChange={(value) => handleInputChange(setImgUrl, value)}
isValid={correctImgUrl}
required
/>

<TextField
name="imdbUrl"
label="Imdb URL"
value=""
value={imdbUrl}
onChange={(value) => handleInputChange(setImdbUrl, value)}
isValid={correctimdbUrl}
required
/>

<TextField
name="imdbId"
label="Imdb ID"
value=""
value={imdbId}
onChange={(value) => handleInputChange(setImdbId, value)}
required
/>

<div className="field is-grouped">
<div className="control">
<button
type="submit"
data-cy="submit-button"
className="button is-link"
className={cn('button', 'is-link', {
'is-disabled': !isFormValid,
})}
disabled={!isValid}
>
Add
</button>
Expand Down
15 changes: 11 additions & 4 deletions src/components/TextField/TextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ type Props = {
placeholder?: string,
required?: boolean,
onChange?: (newValue: string) => void,
isValid?: boolean,
};

function getRandomDigits() {
return Math.random()
return +Math.random()
.toFixed(16)
.slice(2);
}
Expand All @@ -23,13 +24,19 @@ export const TextField: React.FC<Props> = ({
placeholder = `Enter ${label}`,
required = false,
onChange = () => {},
isValid = true,
}) => {
// generage 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 hasError = (touched && required && !value.trim())
|| (!isValid && touched && required);

const handleTouchedChange = (event: React.ChangeEvent<HTMLInputElement>) => {
onChange(event.target.value);
};

return (
<div className="field">
Expand All @@ -47,8 +54,8 @@ export const TextField: React.FC<Props> = ({
})}
placeholder={placeholder}
value={value}
onChange={event => onChange(event.target.value)}
onBlur={() => setTouched(true)}
onChange={handleTouchedChange}
onBlur={() => setTouched((prev) => !prev)}
/>
</div>

Expand Down
Loading