#How do I fetch api route from a solid component
3 messages · Page 1 of 1 (latest)
Hi @hollow bronze. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Astro, you can use the global fetch() function to make HTTP requests to APIs from your Solid component. This function is available in all Astro components, including those built with Solid. Here's an example of how you can use it:
import { createSignal, onMount } from "solid-js";
const Component = () => {
const [data, setData] = createSignal(null);
onMount(async () => {
const response = await fetch('/api/your-endpoint');
const data = await response.json();
setData(data);
});
return (
<div>
{data() && <div>{JSON.stringify(data())}</div>}
</div>
);
};
export default Component;
In this example, we're using Solid's onMount function to fetch data when the component mounts. We then use the fetch() function to make a request to the API endpoint, and store the response in a signal using setData.
Please note that this is a general example and you might need to adjust it according to your specific needs and the structure of your project.