Replies: 2 comments 1 reply
-
I currently use a custom function useTypedParams( paramTypes ) {
const params = useParams();
return Object
.entries(params)
.reduce((accu, [ name, value ]) => {
if ( !paramTypes[ name ] ) {
accu[ name ] = value;
return accu;
}
const paramType = paramTypes[ name ];
if ( paramType === 'string' ) {
accu[ name ] = value;
return accu;
}
if ( paramType === 'bool' ) {
accu[ name ] = Boolean( value );
return accu;
}
if ( paramType === 'int' ) {
accu[ name ] = parseInt( value );
return accu;
}
if ( paramType === 'float' || paramType === 'number' ) {
accu[ name ] = parseFloat( value );
return accu;
}
if ( typeof paramType === 'function' ) {
accu[ name ] = paramType( value );
return accu;
}
console.warn(
`unknown type '${ paramType }' for param ${ name }`
);
accu[ name ] = value;
return accu;
}, {});
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
Very interesting idea! While I generally agree it'd be nicer if the code was a bit more terse, my initial reaction is that this feels like something that belongs in userland as an abstraction. Bundle size is a pretty important metric for us, so we're always weighing DX against shipping as little code as possible. On this matter, a few ideas I've been thinking about:
|
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
What is the new or updated feature that you are suggesting?
I suggest that there is a way of passing an object with type casting definitions to
useParams()
like in the following example:This would show
{ userId: 42, projectId: 1337 }
instead of{ userId: '42', projectId: '1337' }
.There could also be a way of passing a casting function as "type":
If no type is defined it would return string as default. If there is an unknown type the string would be returned with a warning in the console (maybe only in development mode).
Why should this feature be included?
It would shorten the code because and make params more type safe.
Beta Was this translation helpful? Give feedback.
All reactions