diff --git a/src/App.tsx b/src/App.tsx index 34be670b0..703979986 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,16 +1,24 @@ import './App.scss'; +import { useState } from 'react'; 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(moviesFromServer); + + const onAdd = (movie: Movie) => { + setMovies([...movies, movie]); + }; + return (
- +
- {}} */ /> +
); diff --git a/src/components/NewMovie/NewMovie.tsx b/src/components/NewMovie/NewMovie.tsx index 34f22fb0a..742b821af 100644 --- a/src/components/NewMovie/NewMovie.tsx +++ b/src/components/NewMovie/NewMovie.tsx @@ -1,45 +1,104 @@ -import { useState } from 'react'; +import React, { useState } from 'react'; import { TextField } from '../TextField'; +import { Movie } from '../../types/Movie'; -export const NewMovie = () => { +type Props = { + onAdd: (movie: Movie) => void; +}; + +export const NewMovie: React.FC = ({ onAdd }) => { // Increase the count after successful form submission // to reset touched status of all the `Field`s - const [count] = useState(0); + const [count, setCount] = useState(0); + + const [newMovie, setNewMovie] = useState({ + title: '', + description: '', + imgUrl: '', + imdbUrl: '', + imdbId: '', + }); + + const isAllFieldsFilled = newMovie.title.trim() && newMovie.imgUrl.trim() + && newMovie.imdbUrl.trim() && newMovie.imdbId.trim(); + + const handleChange = (e: React.ChangeEvent) => { + const { name, value } = e.target; + + setNewMovie((prevMovie) => ({ ...prevMovie, [name]: value })); + }; + + const reset = () => { + setNewMovie({ + title: '', + description: '', + imgUrl: '', + imdbUrl: '', + imdbId: '', + }); + }; + + const handleFormOnSubmit = (event: React.FormEvent) => { + event.preventDefault(); + + setCount(counter => counter + 1); + + if (!isAllFieldsFilled) { + return; + } + + onAdd(newMovie); + reset(); + }; return ( -
+

Add a movie

{}} + value={newMovie.title} + onChange={handleChange} required />
@@ -48,6 +107,7 @@ export const NewMovie = () => { type="submit" data-cy="submit-button" className="button is-link" + disabled={!isAllFieldsFilled} > Add diff --git a/src/components/TextField/TextField.tsx b/src/components/TextField/TextField.tsx index 307b19865..4c2cc864f 100644 --- a/src/components/TextField/TextField.tsx +++ b/src/components/TextField/TextField.tsx @@ -7,7 +7,7 @@ type Props = { label?: string, placeholder?: string, required?: boolean, - onChange?: (newValue: string) => void, + onChange?: (e: React.ChangeEvent) => void, }; function getRandomDigits() { @@ -39,6 +39,7 @@ export const TextField: React.FC = ({
= ({ })} placeholder={placeholder} value={value} - onChange={event => onChange(event.target.value)} + onChange={(event) => onChange(event)} onBlur={() => setTouched(true)} + />