Home > front end >  Typescript- "property ip doesnt exist on type response"
Typescript- "property ip doesnt exist on type response"

Time:10-24

Hello please can someone else with this typescript error, on this fetch api call I am getting on ip of userIp.ip "property ip doesnt exist on type response", here the code

`
      let userIp = await fetch('https://api.ipify.org?format=json');
      userIp = await userIp.json();
      data = await fetch(
        `https://geo.ipify.org/api/v1? 
      apiKey=at_NWL0fpG63VI0ZH894ZRJh7FexTgjP&ipAddress=${userIp.ip}`
`

CodePudding user response:

First off: never put your private API keys in Stack Overflow questions (or any other online forums as well)! I advise you reset your key as anyone can use them now.

You need to first get the data from the response in JSON before you can access properties off of this. In your first request, you correctly used the Response.json method. However, it seems you forgot to do this in your second which is the cause of your problem:

const userInfoRes = await fetch('https://api.ipify.org?format=json');
const userInfo = await userInfoRes.json();
const dataRes = await fetch(`https://geo.ipify.org/api/v1?apiKey=API_KEY&ipAddress=${userIp.ip}`);
const data = await dataRes.json();

CodePudding user response:

I think it's because you declare

let userIp = await fetch('https://api.ipify.org?format=json');

userIp is of type Response.

Then with userIp = await userIp.json();, since userIp.json() returns a Promise<any>, it is the same as

userIp: Response = await userIp.json();

And it doesnt find the ip key in Response

Using another variable fixes it

  let userIp = await fetch('https://api.ipify.org?format=json');
  let userIpJson = await userIp.json();
  //You can also put a constraint
  //let userIpJson : { ip: string } = await userIp.json();
  console.log(userIpJson.ip)
  • Related