Next.js Discord

Discord Forum

Error handling when No error.

Answered
Ocicat posted this in #help-forum
Open in Discord
OcicatOP
Im following a tutorial seems to be on a older version of Next.js this seems to work prior but now its throwing an error.
error is not defined

This is the code
export default function DeleteIcon({ id }) {
    const [isLoading, setIsLoading] = useState(false)
    const router = useRouter()
  
    const handleClick = async () => {
      setIsLoading(true)
      
      const res = await fetch(`http://localhost:3000/api/tickets/${id}`, {
        method: 'DELETE'
      })
      const json = await res.json()
  
      if (json.error) {
        console.log(error)
        setIsLoading(false)
      }
      if (!json.error) {
        router.refresh()
        router.push('/tickets')
      }
    }

What is the best way to resolve this issue or best practice.
Answered by Ocicat
export default function DeleteIcon({ id }) {
    const [isLoading, setIsLoading] = useState(false)
    const router = useRouter()
  
    const handleClick = async () => {
      setIsLoading(true)
      
      const res = await fetch(`http://localhost:3000/api/tickets/${id}`, {
        method: 'DELETE'
      })
      const json = await res.json()
  
      if (json.error) {
        console.log(.json.error) //< add json.
        setIsLoading(false)
      }
      if (!json.error) {
        router.refresh()
        router.push('/tickets')
      }
    }
View full answer

5 Replies

Ideally you would first try and fix the error
but if thats not possible.. couldnt you just catch the error and render a not sucessfull message?
also send the json response if thats possible
OcicatOP
export default function DeleteIcon({ id }) {
    const [isLoading, setIsLoading] = useState(false)
    const router = useRouter()
  
    const handleClick = async () => {
      setIsLoading(true)
      
      const res = await fetch(`http://localhost:3000/api/tickets/${id}`, {
        method: 'DELETE'
      })
      const json = await res.json()
  
      if (json.error) {
        console.log(.json.error) //< add json.
        setIsLoading(false)
      }
      if (!json.error) {
        router.refresh()
        router.push('/tickets')
      }
    }
Answer
OcicatOP
Thanks for the help