please doee anyone have an idea how the first code works and the second doesn't? i saw the first code somewhere and i have been trying to understand the idea behind it. thanks
const loadable = (importFunc, { fallback = null } = { fallback: null }) => {
const LazyComponent = lazy(importFunc);
return props => (
<Suspense fallback={fallback}>
<LazyComponent {...props} />
</Suspense>
);
};
When you destructure in the argument list with an object, an identifier after a colon indicates the new variable to put the property into.
This:
const test2 = ({ fallback: foo }) => {
// rest of function
means
const test2 = (parameter) => {
let foo = parameter.fallback;
// rest of function
But you're not using foo, but null - which the interpreter (and specification) recognizes as almost certainly being an accidental error. You don't want to put a value into an identifier named null, so it prohibits you from doing so.
Neither of the codes you provided are valid syntax for this reason.
If you just want to put the fallback property of the argument into a variable, omit the colon.
const test2 = ({ fallback }) => {
console.log(fallback);
}
//calling
test2({fallback: "hello"});
If you also want to provide a default value in case the property is undefined, use = (not :).
const test2 = ({ fallback = null }) => {
console.log(fallback);
}
//calling
test2({fallback: "hello"});
test2({});
If you also want to provide a default value for the whole object argument in case no arguments are passed, use another = after the argument is listed (very similar to what you're doing originally, but, again, with =, not :)
const test2 = ({ fallback = null } = {}) => {
console.log(fallback);
}
//calling
test2({fallback: "hello"});
test2({});
test2();