Home > Blockchain >  adding data type to fetch response
adding data type to fetch response

Time:10-03

interface IUsers {
  id: number;
  name: string;
}

export const fetchUsers = () =>
  fetch(`/users`).then((res) => res.json());

How do I add IUsers type to fetchUsers response? fetchUsers return [{id:1, name:'fay'}].

CodePudding user response:

Assuming that you have already written this:

export interface iUsers {
    id : number
    name : string
}

Modify your method like this:

export const fetchUsers = async () : Promise<{ data : iUsers[] }>  => {
    const response = await fetch(`/users`) ;
    const data : iUsers[]= await response.json() 
    return { data  }
  }

And use it like this :

const { data } = await fetchUsers();

You can hover on your IDE for the hints, it will show that data is an iUsers[]

EDIT This is the shorted version you wanted, which might not match your requirements

export const fetchUsers = async () : Promise<iUsers[] >  => await (await fetch(`/users`)).json() ;

and use it like this :

const data = await fetchUsers()
  • Related