SSubedi
SSubedi

Reputation: 121

Call a JSONP API with React

I am trying to call an API that is given to me. First, I did not understand the question. The API given to me looks like 'test.com/a/b/c/d/d' and it also says:

callback parameter name: 'jsonp'.

I tried things like adding ?callback='jsonp' at the end of the API and other few things. I am trying to call this API and display the result. I am using React on CodeSandBox and I used the fetch() function to make this call. I keep getting error saying it failed. The API is correct but I just don't understand how I add that callback parameter. I have fetched other JSON based APIs before but this time I am doing something wrong, especially withe this JSONP things. Please help.

Edit** When I put that API in the browser, I do get actual data back. But it in this format /**/invalidCallbackFunctionName([ {DUMMY_DATA1}, {DUMMY_DATA2},.....]) So clearly the API works, it's just that the way I am calling it and the way JSONP works, I am missing something in the code.

Upvotes: 1

Views: 3341

Answers (1)

SSubedi
SSubedi

Reputation: 121

Turns out I was not using the right package and the correct way. Here is what works:

import fetchJsonp from "fetch-jsonp";

 fetchJsonp("https:/www.a.com/b/c/d", {
    jsonpCallback: "jsonp"
  })
    .then((res) => res.json())
    .then((data) => console.log(data));

Upvotes: 3

Related Questions