I have query with several params, and I want to add params to query only if is not null.
Only thing I came up with create params object and conditionally add properties, but adding this for every query feels like wrong way, cause I think there is better way to handle with this My solution:
query: (category: string | null) => {
const params: { [key: string]: string } = {};
if (category !== null) params.category = category;
return {
url: "/products",
params: params,
};
},
You can write a general function that performs a Depth / Breadth First Traversal over the input object graph to modify (or copy + modify) it so that null properties are deleted or set to undefined.
I use a similar function in my code with RTK Query to perform serialization and deserialization to / from my back-end API.
EDIT: Here is a copy of my Depth First Traversal implementation for traversing a javascript object graph. It is generic and can be used for both pre- and post- traversals. I've written a number of unit tests for it in my own code and it works well.
If you wanted to use it to traverse an object graph and to modify all of the null properties to be undefined, then you could define a visit function like so (NOTE: This bit hasn't been tested / debugged, and may require special care for array entries):
Alternatively, you could just delete the property like so:
delete parent[field];You can apply this with my earlier function to iterate over your input object graph (
params) like so: