Home > Back-end >  Error message : SyntaxError: Unexpected token < in JSON at position 0
Error message : SyntaxError: Unexpected token < in JSON at position 0

Time:07-09

i was trying to fetch a data for a project but everytime i'm converting the fetch data to json it returns me

SyntaxError: Unexpected token < in JSON at position 0

i don't understand why it's showing me this

import React,{useContext,useState,useEffect} from 'react'

const url = 'www.thecocktaildb.com/api/json/v1/1/search.php?s='


export default function AppProvider({children}) {
    const [loading,setLoading] = useState(true)
    const [searchTerm,setSearchTerm] = useState('a') 
//set it as 'a' for suggestion at search bar at beginning.
    const [cocktails,setCocktails] = useState([])

    const fetchUrl = async ()=>{
        setLoading(true)
        try {
            const response = await fetch(`${url}${searchTerm}`)
//(${url}${searchterm} helps me to fetch data at first with names that starts with 'a' for suggestion///
            const data = await response.json()
            setLoading(false)
        } catch (error) {
            console.log(error)
        }
    }

    useEffect(()=>{
        fetchUrl()
    },[searchTerm])

please visit the API page from the URL & see if there's an issue with the data. the data is not fetching. what's the issue?

Link

CodePudding user response:

Doing

fetch('www.thecocktaildb.com/')

will fetch not that website, but that path relative to the current path. For example, doing so here on Stack Overflow results in the URL being fetched being

https://stackoverflow.com/questions/72914244/www.thecocktaildb.com/

which, of course, doesn't exist - and presumably that URL doesn't exist on your site either.

Use the full path.

const url = 'https://www.thecocktaildb.com/api/json/v1/1/search.php?s='

I'd also recommend only calling the API when searchTerm isn't empty, and perhaps add a debounce of a few hundred milliseconds so as not to call it too often and to keep the client from being blocked.

  • Related