Fetching api route during different states
Unanswered
Asiatic Lion posted this in #help-forum
Asiatic LionOP
hi there! I'm trying to use a method I made that fetches my api route (/api/search) and for some reason, it doesn't seem to work in different use cases. The first use case is a call on the method that happens when a user inputs a form, so everything on the server is already rendered. The method is called on a client component and works just fine. The second use case is calling the same method simply in the function for a client component that's rendered on a different page. That means the component is rendered on the page and the method is immediately called. For whatever reason, I'm running into the error "Failed to parse URL from /api/search" from this use case. This is referring to a simple line
This component is called in a very simple page.
im not sure if this is happening because im straight up calling the method without waiting for things to render, but im not really sure how to wait for things to render before calling the method either. any guidance or help is appreciated!
fetch('api/search') that works in the first use case, but causes the invalid URL error in the second. Here is the structure for the second use case that doesn't seem to be working export default function ConfirmParam() {
const searchParams = useSearchParams();
const confirm = searchParams.get('id');
const [searchResults, setSearchResults] = useState(null);
if(!confirm) {
return <Redirect to="/"/>
}
if(!searchResults) {
//getSearchResults is the method that fetches the api
getSearchResults(confirm).then((results) => {
setSearchResults(results);
});
}
// more code...This component is called in a very simple page.
export default function Home() {
return (
<main className="flex min-h-screen flex-col items-center justify-between p-0 sm:p-10 w-full">
<section className="flex flex-col items-center justify-center w-full">
<ConfirmParam />
</section>
</main>
);
}im not sure if this is happening because im straight up calling the method without waiting for things to render, but im not really sure how to wait for things to render before calling the method either. any guidance or help is appreciated!
4 Replies
Asiatic LionOP
bump!
Just a thought, but could it be because you are using a relative url and not a full url such as http://localhost:3000/api/search? Try that and see what happens. Use an environment variable to get the base URL.
Asiatic LionOP
oh thats smart, then i could set the production url when deploying
ill try that later, but id still love to know why this is happening at all if anyone knows ðŸ™