satya
Tue Aug 22 2023
Let's say we have an api function
export const getTheResults = async (params) => {
const response = await axios.get(
/api/v1/example.json?${stringify(params)}
);
return response.data;
};
the param
is an object mentioned below , and we are stringifying it before sending the request to backend.
Note: we are using stringify
from qs
npm package.
const params = {
key1: "value1",
key2: "value2",
key3: ["value3", "value4"],
}
the stringified output will be - > key1=value1&key2=value2&key_3%5B0%5D=value3&key_3%5B1%5D=value4
i.e key1=value1&key2=value2&key_3[0]=value3&key_3[1]=value4
but backend is expecting to receive it without the index values i.e key1=value1&key2=value2&key_3[]=value3&key_3[]=value4
So in order to send the parameters like that , we can just pass a stringify option called arrayFormat: "brackets"
eg: export const getTheResults = async (params) => {
const response = await axios.get(
/api/v1/example.json?${stringify(params, {arrayFormat: "brackets"})}
);
return response.data;
};