-
Notifications
You must be signed in to change notification settings - Fork 454
/
FeedbackForm.jsx
88 lines (76 loc) · 2.47 KB
/
FeedbackForm.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { useState, useContext, useEffect } from 'react'
import RatingSelect from './RatingSelect'
import Card from './shared/Card'
import Button from './shared/Button'
import FeedbackContext from '../context/FeedbackContext'
function FeedbackForm() {
const [text, setText] = useState('')
const [rating, setRating] = useState(10)
const [btnDisabled, setBtnDisabled] = useState(true)
const [message, setMessage] = useState('')
const { addFeedback, feedbackEdit, updateFeedback } =
useContext(FeedbackContext)
useEffect(() => {
if (feedbackEdit.edit === true) {
setBtnDisabled(false)
setText(feedbackEdit.item.text)
setRating(feedbackEdit.item.rating)
}
}, [feedbackEdit])
// NOTE: This should be checking input value not state as state won't be the updated value until the next render of the component
// prettier-ignore
const handleTextChange = ({ target: { value } }) => { // 👈 get the value
if (value === '') {
setBtnDisabled(true)
setMessage(null)
// prettier-ignore
} else if (value.trim().length < 10) { // 👈 check for less than 10
setMessage('Text must be at least 10 characters')
setBtnDisabled(true)
} else {
setMessage(null)
setBtnDisabled(false)
}
setText(value)
}
const handleSubmit = (e) => {
e.preventDefault()
if (text.trim().length > 10) {
const newFeedback = {
text,
rating,
}
if (feedbackEdit.edit === true) {
updateFeedback(feedbackEdit.item.id, newFeedback)
} else {
addFeedback(newFeedback)
}
// NOTE: reset to default state after submission
setBtnDisabled(true) // 👈 add this line to reset disabled
setRating(10) //👈 add this line to set rating back to 10
setText('')
}
}
// NOTE: pass selected to RatingSelect so we don't need local duplicate state
return (
<Card>
<form onSubmit={handleSubmit}>
<h2>How would you rate your service with us?</h2>
<RatingSelect select={setRating} selected={rating} />
<div className='input-group'>
<input
onChange={handleTextChange}
type='text'
placeholder='Write a review'
value={text}
/>
<Button type='submit' isDisabled={btnDisabled}>
Send
</Button>
</div>
{message && <div className='message'>{message}</div>}
</form>
</Card>
)
}
export default FeedbackForm