[React] Write a Custom React Effect Hook

Similar to writing a custom State Hook, we’ll write our own Effect Hook called useStarWarsQuote, which returns a random quote and a loading state.json

Remember, hooks can only be used inside function components.api

 

function useStarWarsQuote() {
  // defualt the quote to a empty value
  const [quote, setQuote] = useState('')
  // default the loading to false
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    async function getStarWarsQuote() {
      setLoading(true)
      // Get initial text
      const response = await fetch(
        'https://starwars-quote-proxy-gi0d3x1lz.now.sh/api/randomQuote'
      )
      const data = await response.json()
      const quote = data.starWarsQuote
      setQuote(quote)
      setLoading(false)
    }
    getStarWarsQuote()
  }, [])

  return { quote, loading }
}
export function FeedbackCustomComponent() {
  const [text, setText] = useText('')
  const { quote, loading } = useStarWarsQuote()

  useEffect(() => {
    if (quote) {
      setText(quote)
    }
  }, [quote, setText])
  // Handle form submission
  function handleSubmit(e) {
    e.preventDefault()
    console.log(`Submitting response to API: "${text}"`)
    setText('')
  }

  // Update text in state onchange for textarea
  function handleTextChange(e) {
    const updatedText = e.target.value

    setText(updatedText)
  }

  if (loading) return <p>Loading...</p>

  if (quote) {
    return (
      <Form onSubmit={e => handleSubmit(e)}>
        <Title>Custom Example</Title>
        <Label>
          Have feedback for our team? <br /> Let us know here 👇
        <Textarea value={text} onChange={e => handleTextChange(e)} />
        </Label>
        <Button type="submit">Submit</Button>
      </Form>
    )
  }

  return null
}
相關文章
相關標籤/搜索