moias
moias3y ago

Fresh fetch data in component

Hi I need help with Preact, I would like to do a fetch in a component using Handlers and then use that data in the same component without the component having props that would interfere with the parent component.
4 Replies
moias
moiasOP3y ago
LanguageToggle.tsx (child component) - island
export const handler: Handlers<ILanguageModel | null> = {
async GET(_, ctx) {
const resp = await fetch(`http://localhost:8000/api/languages/default`);
if (resp.status === 404) {
return ctx.render(null);
}
const data: ILanguageModel = await resp.json();
return ctx.render(data);
},
};

export default function LanguageToggle(data: ILanguageModel) {
const [language, setLanguage] = useState(data.id);

return (
<div className="menu-operators">
{JSON.stringify(language)}
</div>
);
}
export const handler: Handlers<ILanguageModel | null> = {
async GET(_, ctx) {
const resp = await fetch(`http://localhost:8000/api/languages/default`);
if (resp.status === 404) {
return ctx.render(null);
}
const data: ILanguageModel = await resp.json();
return ctx.render(data);
},
};

export default function LanguageToggle(data: ILanguageModel) {
const [language, setLanguage] = useState(data.id);

return (
<div className="menu-operators">
{JSON.stringify(language)}
</div>
);
}
Menu.tsx (parent component) - component
export function Menu() {
return (
<nav>
<a href="/" className="logo">
<img src="/logo.svg" alt="Logo" />
</a>
<ul className="links-list">
<li className="link">
Hello
</li>
<li className="language-toggle">
<LanguageToggle />
</li>
</ul>
<MenuToggle />
</nav>
);
}
export function Menu() {
return (
<nav>
<a href="/" className="logo">
<img src="/logo.svg" alt="Logo" />
</a>
<ul className="links-list">
<li className="link">
Hello
</li>
<li className="language-toggle">
<LanguageToggle />
</li>
</ul>
<MenuToggle />
</nav>
);
}
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
moias
moiasOP3y ago
I know, but i just wanna fetch inside component no inside view
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?