Correct way to use Axios with TypeScript

Viewed 9443

I have an error in my application that I can't seem to solve. I use axios with TypeScript. Here's a code example of what I try to do:

export const fetchTransactions = (PageNum: number, PageSize: number, Context_id: number) => new Promise<Transaction[]> (async (resolve, reject) => {

  try
  {
    const response = await axios.post<AxiosResponse<Transaction[]>>(FETCH_TRANSACTIONS_URL, {PageNum, PageSize, Context_id})
    const {transactions} = response.data
    resolve(transactions)
  }
  catch (error) {
    reject(error.response);
  }
})

Now the error that I get for this const {transactions} = response.data is the following : enter image description here

How can I remove this error? What should be the correct type of the response?

1 Answers

Normally, I use axios with Typescript this way

const fetchTransactions = (PageNum: number, PageSize: number, Context_id: number): Promise<Transaction[]> =>
  axios
    .post<Transaction[]>(FETCH_TRANSACTIONS_URL, {PageNum, PageSize, Context_id})
    .then((response) => {
      if (response.status >= 200 && response.status < 300) {
        return response.data;
      }
      throw new Error(response.status.toString());
    })
    .catch(({ response }) => {
      throw new Error(response.status);
    });
Related