Home > Software engineering >  Cannot enter in catch error on this API call
Cannot enter in catch error on this API call

Time:09-15

I'm trying to create a custom hook and i would like to catch an error on the api call in order to change the display. This is the custom hook :

function useBook() {
    const [book, setBook] = useState<Book | any>()
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState<Error | boolean>(false)

    useEffect(() => {
        const fetchData = async () => {
            try {
                const data = await getBook(Number(Object.values(id)))
                setBook(data)
                setLoading(false)
            } catch (error) {
                setError(true)
                setLoading(false)
            }
        }
        fetchData()
        dispatch({ type: 'auth/isLogin' })
    }, [])

    return { book, loading, error }
}

And this is the api function :

export type Book = {
    title: string
    id: number
    authorName: string
    authorSurname: string
    coverImage: string
    releaseDate: string
    pages: number
    price: number
}

export type Error = {
    isError: boolean
}

async function getBook(id: number): Promise<Book | Error> {
    try {
        const { data } = await axios.get<Book>(
            `http://localhost:3000/books/${id}`,
            {
                headers: {
                    Accept: 'application/json',
                },
            }
        )
        return data
    } catch (error) {
        console.log('Error is : ', error)
        return {
            isError: true,
        }
    }
}

The problem is that I never enter in the 'catch error' case and thus the state of error is always false. How could I change that ?

CodePudding user response:

Trying throwing an error instead of return:

export type Book = {
    title: string
    id: number
    authorName: string
    authorSurname: string
    coverImage: string
    releaseDate: string
    pages: number
    price: number
}

export type Error = {
    isError: boolean
}

async function getBook(id: number): Promise<Book | Error> {
    try {
        const { data } = await axios.get<Book>(
            `http://localhost:3000/books/${id}`,
            {
                headers: {
                    Accept: 'application/json',
                },
            }
        )
        return data
    } catch (error) {
        console.log('Error is : ', error)
        throw new Error("error")
    }
}
  • Related