Created
November 3, 2021 20:13
-
-
Save tomaszzmudzinski/dc00599c54802b0de1161225353b4f4b to your computer and use it in GitHub Desktop.
Post using RTK Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; | |
import { Product } from 'app/types/product'; | |
interface ProductListResponse { | |
endIndex: number; | |
products: Product[]; | |
startIndex: number; | |
totalItems: number; | |
totalPages: number; | |
} | |
interface ProductListQuery { | |
sortBy: string; | |
search: string; | |
locale: string; | |
filters: ProductListFilter[]; | |
category?: number; | |
} | |
export interface ProductListFilter { | |
key: number; | |
value: number; | |
} | |
export const productListApi = createApi({ | |
reducerPath: 'productListApi', | |
baseQuery: fetchBaseQuery({ | |
baseUrl: `${process.env.NEXT_PUBLIC_API}/api/products/`, | |
}), | |
endpoints(build) { | |
return { | |
getProductList: build.query({ | |
query: ({ sortBy, search, locale, filters, category }) => ({ | |
url: buildProductsQuery( | |
`getProductList?page=1&pageSize=50&sortBy=${sortBy}&language=${locale}`, | |
search, | |
filters, | |
category | |
), | |
method: 'post', | |
}), | |
}), | |
}; | |
}, | |
}); | |
const buildProductsQuery = ( | |
url: string, | |
search: string, | |
filters: ProductListFilter[], | |
category?: number | |
) => { | |
if (search) { | |
url = `${url}&search=${search}`; | |
} | |
if (filters && filters.length) { | |
filters.forEach((filter) => { | |
url = `${url}&filters={${filter.key}, ${filter.value}}`; | |
}); | |
} | |
if (category) { | |
url = `${url}&category=${category}`; | |
} | |
return url; | |
}; | |
export const { useGetProductListQuery } = productListApi; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment