I am trying to implement filter on API before fetching.
I have a dynamic API route([productType]), which works fine. But when I try to filter the API, it doesn't work.
So the syntax for filtering API looks like this ?$filter=name eq 'Milk' and adding this to the url doesn't work.
As in docs says, I have a tried to change the filename like this [...productType] or [[...productType]] but none of them helps.
It returns the api data without filtering.
Here is my code in API dynamic route[productType]. pages/api/[productType]
import axios, { AxiosRequestConfig, Method } from 'axios'
import { pick } from 'lodash'
import { NextApiRequest, NextApiResponse } from 'next'
const baseUrl ='https://myUrl...'
const getFromAPIServer = async (
req: NextApiRequest,
res: NextApiResponse,
) => {
const { productType } = req.query
const param = req.query.params //here I tried to add the parameter for filter, which doesn't work
const url = `${baseUrl}/${productType}?${param}?`
const method = req.method as Method
const { body } = req
const allowedHeaders = ['If-Match']
const headers = pick(req.headers, allowedHeaders) as Record<string, string>
try {
const request: AxiosRequestConfig = {
method,
url,
headers: {
...headers,
Authorization: `Basic ${process.env.TOKEN}`,
'Content-Type': 'application/json',
},
}
if (method !== 'GET' && body) {
request.data = body
}
const { data } = await axios.request(request)
res.status(200).json(data)
} catch (error) {
if (!axios.isAxiosError(error)) {
throw error
}
// Return AxiosError to the client
res.status(error?.response?.status || 500).json(error?.response?.data)
}
}
export default getFromAPIServer
And in components I have the fetching function where I try to fetch the api with filter
export const getApiRequest = (url: string) => {
const { data } = useQuery(['key', url], async () => {
const response = await fetch(url, {
method: 'get',
})
if (!response.ok) throw new Error(response.statusText)
return await response.json()
})
return { data }
}
const { data } = getApiRequest(`${productTypeUrl}?$filter=name eq 'Milk'`)
Forgot to mention: In Postman filtering, the API works fine. It works also fine when I try to fetch with the filter url in components, not importing from api folder.
Doing the filtering in api folder works as below
const url = `${baseUrl}/${productType}?$filter=name eq 'Milk'?`
However, this is not what I want. I want to have filter as params on API folder, like productType so that I can use it on client side.
Any help will be appreciated