How to call external APIs?

Hi, I need to make external requests to some API endpoints, i can do that with axios but i want to know how to handle this better in this framework.

For Example, Requesting WP with JWT Authentication Plugin Installed to get Token and authenticate users.

I would also appreciate if somebody explains how to redirect to any other page, in my case it would be a dashboard.

Thanks!

Hi @aeyzazkhan!

We have already made fetch importable from frontity so it works in both the server and the client with the same code. For calling external API we recommend to import fetch from frontity and use it as usual.

import { fetch } from "frontity";

const data = fetch("externalURL")

This way, fetch will work in server and client, making it easier.

Could you explain this case a bit more, please? The dashboard where you want to redirect, is it external or is it another page of your web?

Please, let us know if the fetch works for you or share any questions you may have :slight_smile:

Thank you for explanation, shall i directly call the fetch in the page or its better to create a handler somewhere and then call it on my lets say sign in page.

I want users to be directed to Dashboard within the application after they are authenticated.

Hey @aeyzazkhan, that’s easy!

You just have to change the URL using actions.router.set.

// After authentication...
actions.router.set(dashboardUrl);

Thank you!

Handlers are useful when you want to “link” some data to a URL (or set of URLs).

The main benefit is that after creating the handler you don’t need to worry about fetching that data neither in the server or the client. It just works.

But if you are fetching data that is not important for SSR, like for example info after the user has logged in, it’s fine to do it with a normal fetch.

We use window.fetch instead of axios to avoid adding those KBs to the bundle. But import it from frontity as Mario explained so it works in the server as well.

1 Like