@@ -6,7 +6,16 @@ import React, { useEffect, useState } from "react";
66import toast from "react-hot-toast" ;
77
88const AddNewProduct = ( ) => {
9- const [ product , setProduct ] = useState < { title : string ; price : number ; manufacturer : string ; inStock : number ; mainImage : string ; description : string ; slug : string ; categoryId : string ; } > ( {
9+ const [ product , setProduct ] = useState < {
10+ title : string ;
11+ price : number ;
12+ manufacturer : string ;
13+ inStock : number ;
14+ mainImage : string ;
15+ description : string ;
16+ slug : string ;
17+ categoryId : string ;
18+ } > ( {
1019 title : "" ,
1120 price : 0 ,
1221 manufacturer : "" ,
@@ -19,7 +28,15 @@ const AddNewProduct = () => {
1928 const [ categories , setCategories ] = useState < Category [ ] > ( [ ] ) ;
2029
2130 const addProduct = async ( ) => {
22- console . log ( product ) ;
31+ if (
32+ product . title === "" ||
33+ product . manufacturer === "" ||
34+ product . description == "" ||
35+ product . slug === ""
36+ ) {
37+ toast . error ( "Please enter values in input fields" ) ;
38+ return ;
39+ }
2340
2441 const requestOptions : any = {
2542 method : "post" ,
@@ -28,9 +45,9 @@ const AddNewProduct = () => {
2845 } ;
2946 fetch ( `http://localhost:3001/api/products` , requestOptions )
3047 . then ( ( response ) => {
31- if ( response . status === 201 ) {
48+ if ( response . status === 201 ) {
3249 return response . json ( ) ;
33- } else {
50+ } else {
3451 throw Error ( "There was an error while creating product" ) ;
3552 }
3653 } )
@@ -46,7 +63,8 @@ const AddNewProduct = () => {
4663 slug : "" ,
4764 categoryId : "" ,
4865 } ) ;
49- } ) . catch ( error => {
66+ } )
67+ . catch ( ( error ) => {
5068 toast . error ( "There was an error while creating product" ) ;
5169 } ) ;
5270 } ;
@@ -78,6 +96,16 @@ const AddNewProduct = () => {
7896 } )
7997 . then ( ( data ) => {
8098 setCategories ( data ) ;
99+ setProduct ( {
100+ title : "" ,
101+ price : 0 ,
102+ manufacturer : "" ,
103+ inStock : 1 ,
104+ mainImage : "" ,
105+ description : "" ,
106+ slug : "" ,
107+ categoryId : data [ 0 ] ?. id ,
108+ } ) ;
81109 } ) ;
82110 } ;
83111
0 commit comments