[Feature] : Add a default value for data
TomPradat opened this issue · comments
As initialValue
only works for server-side rendering, it could be nice to have another prop (ex: defaultDataValue
) so that we can controll the initial value of data
.
This would improve developer experience with the lib.
What's stopping you from using initialValue
on the client side?
Alternatively, why not use some plain JavaScript to fall back to a default value?
When using the initialValue on the client side, the promiseFn
is never called.
As using plain JS, this is what I'm doing but i though it would be less painful having this shipped in the library :
const { data: { todos, userPreferences } } = useAsync({ promiseFn, defaultDataValue: { todos: [], userPreferences: null } });
vs
const { data } = useAsync({ promiseFn });
const todos = data ? data.todos : [];
const userPreferences = data ? data.userPreferences : null;
I agree this is not a mandatory feature but I though this could improve developer experience.
I'm willing to work on this if you're convinced
How about:
const { data } = useAsync({ promiseFn });
const { todos = [], userPreferences = null } = data;
To be honest I don't think it's worth adding more API options if it can be avoided with a single line of code on the consumer side.
Yeap i undestand.
Your code doesn't work though because const { todos = [], userPreferences = null } = undefined;
throws.
Thank you for your time anyway 👍
That's easily fixed:
const { data } = useAsync({ promiseFn });
const { todos = [], userPreferences = null } = data || {};
Though i really like the solution of @ghengeveld still i kind of agree with OP on this. It would be beneficial to have defaultValue