Encoding and Decoding Search Params
Provide examples of how to encode search parameters to handle special characters and decode them back, leveraging TanStack Router's custom serialization capabilities.
const encodeSearchParams = (params) => {
const searchParams = new URLSearchParams();
Object.keys(params).forEach(key => {
searchParams.set(encodeURIComponent(key), encodeURIComponent(params[key]));
});
return searchParams.toString();
}
This function takes an object of key-value pairs and encodes them into a URL search string. It ensures that special characters in keys and values are correctly encoded.
const decodeSearchParams = (search) => {
const params = new URLSearchParams(search);
const decodedParams = {};
params.forEach((value, key) => {
decodedParams[decodeURIComponent(key)] = decodeURIComponent(value);
});
return decodedParams;
}
This function takes a URL search string, decodes it, and returns an object where both keys and values are decoded, handling special characters correctly.
// Example Usage
const encoded = encodeSearchParams({ 'special char': 'value&more', 'anotherParam': 'yes/no' });
console.log(encoded); // special%20char=value%26more&anotherParam=yes%2Fno
const decoded = decodeSearchParams(encoded);
console.log(decoded); // { 'special char': 'value&more', 'anotherParam': 'yes/no' }
Demonstration on how to use the encode and decode functions with a sample object containing special characters. It shows the encoded search string and then decodes it back to the original object.