Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error message : SyntaxError: Unexpected token < in JSON at position 0

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 & please help me to solve this ASAP!! the data is not fetching & please let me know what’s the issue!
Link:

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading