compiler
compiler copied to clipboard
🐛 BUG: Switch statements break with case brackets
What version of astro
are you using?
1.0.0-beta.34
Are you using an SSR adapter? If so, which one?
None
What package manager are you using?
yarn
What operating system are you using?
Mac
Describe the Bug
When using a switch statement inside an astro component, a transformer error occurs if using curly braces for the switch cases.
Error:
Transform failed with 1 error: /home/projects/github-vsdeec/src/pages/index.astro:67:6: ERROR: Unexpected "return"
Occurs with:
{items.map(({ type, ...data }) => {
switch (type) {
case 'card': {
return (
<Card {...data} />
);
}
case 'paragraph': {
return (
<p>{data.body}</p>
);
}
default: {
return (
<strong>Unknown type</strong>
);
}
}
})}
But not with:
{items.map(({ type, ...data }) => {
switch (type) {
case 'card':
return (
<Card {...data} />
);
case 'paragraph':
return (
<p>{data.body}</p>
);
default:
return (
<strong>Unknown type</strong>
);
}
})}
Link to Minimal Reproducible Example
https://stackblitz.com/edit/github-vsdeec?file=src/pages/index.astro
Participation
- [ ] I am willing to submit a pull request for this issue.
This is a compiler bug, so I'm going to move it over to that repo!
I have encountered the same issue using if
statements and found it only happens if there is an open curly-brace following a self-closing tag.
---
const items = [
'hr',
'Something else',
];
---
<!-- This works -->
{items.map((item) => {
if (item === 'hr') return <hr />;
if (item === '') return <p>Nothing</p>;
return <p>{item}</p>;
})}
<!-- This works -->
{items.map((item) => {
if (item === 'hr') {
return <hr />;
}
if (item === '') return <p>Nothing</p>;
return <p>{item}</p>;
})}
<!-- This works -->
{items.map((item) => {
if (item === 'hr') {
return <strong>hr</strong>;
}
if (item === '') {
return <p>Nothing</p>;
}
return <p>{item}</p>;
})}
<!-- This does not work -->
{items.map((item) => {
if (item === 'hr') {
return <hr />;
}
if (item === '') {
return <p>Nothing</p>;
}
return <p>{item}</p>;
})}
I had encountered same problem. Any progress?
Yes, another place this falls down at present is when trying to use variables inside a block. I think not just a switch block, but there for sure, and without :
switch (slice.type) {
case 'rich_text': {
const boom = funcToGetHtml(slice);
return <div set:html={ boom }></div>
}
....
}
Error: unexpected const, at (very wrong line, about three times as many as are in the .astro file)
This seemed to happen no matter how I rearranged the file , anywhere const appeared between brackets, boom.
Workaround for the present was to make another component, send the slice to it to prepare the rich text div, return that component for the rich text case in the switch..