0

I'm trying to pass an API URL that's has it's params manipulated with the URLSearchParams interface, and I would like to pass that result to an adapter class to fetch that url. As a JS newbie, I am struggling to pass the URL generated in one class to the fetch method in the adapter class. Any ideas? Here is an example. Thank you.

 class Search {

    constructor() {
        this.adapter = new StocksAdapter()
        this.baseUrl = "https://www.alphavantage.co/query?"
        this.baseUrlAPI = "https://www.alphavantage.co/queryfunction=TIME_SERIES_DAILY&symbol=CCL&apikey=demo"
    }

    symbolQuery(paramSymbol) {
        const url = new URL(this.baseUrlAPI)
        const params = new URLSearchParams(url.search)
        params.set("symbol", `${paramSymbol}`)
        let searchUrl = this.baseUrl.concat(params).toString()
        this.adapter.fetchSymbol(this.searchUrl)


    }
}


class StocksAdapter {

    constructor() {}

    fetchSymbol(searchUrl) {
        return fetch(searchUrl)
            .then(res => res.json())
    }
}
ajgu
  • 1
  • 1
  • Why not make a URL class that contains the scheme, full domain, path, and a map of parameters with methods to mutate the parameters. Then just have a toString method that constructs the full url with everything. – Bren Jul 08 '20 at 06:19
  • Could you explain what's happening as how your passing looks fine. Are you getting any errors in the console? – Keith Jul 08 '20 at 06:26
  • It seems to want to return the actual object instead of the url the object creates.I get the following error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 stocksAdapter.js:34 GET http://127.0.0.1:5500/api_project/stock_info_app/front_end/undefined 404 (Not Found) fetchSymbol @ stocksAdapter.js:34 symbolQuery @ search.js:54 (anonymous) @ stocks.js:70 – ajgu Jul 08 '20 at 21:03
  • That's usually because the url you supplied is not returning JSON, it's likely returning just HTML. – Keith Jul 09 '20 at 08:11

0 Answers0