I found a solution to my project to use api-platform/admin
aka react-admin
and show some data how I want. I also implemented the authentication (JWT), login page, etc. The frontend application loads resources and I don’t have any problem with it. I also defined my httpClient
and apiDocumentationParser
and any request to API by the default data provider included the header with the bearer token.
const getHeaders = (): HeadersInit => {
const userToken = token();
return {
Authorization: `Bearer ${userToken}`,
};
};
const httpClient = (url: URL, options: any = {}) => {
return baseFetchHydra(url, {
headers: getHeaders,
});
};
const apiDocumentationParser = async (entrypointUrl: string) => {
//....
}
But I also created a custom endpoint in my backend (sf6 + api-platform) which I want to use in my frontend that I meant above. I’ve created a button component and on the onClick action, I want to send a request to this custom endpoint. Now I have a problem. I can create a request by fetch
but I need to add the header with Bearer manually. I read about useDataProvider
but it allows sending the default request or I need to define a new one (honestly, I don’t know how)
const doSomething = async (id: string) => {
const auth = localStorage.getItem("auth");
const token = JSON.parse(auth ?? ``).token;
const request = new Request(
process.env.REACT_APP_API_URL + "/this_custom_endpoint/{id}".replace("{id}", id),
{
method: "GET",
headers: new Headers({
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
}),
}
);
return fetch(request).then(...).then(...).catch(...);
}
const DoSomethingButton = () => {
const record = useRecordContext();
return (
<Button
label="Do something"
onClick={() => {
const id = record.originId;
doSomething(id);
}}
/>
);
};
The button is displayed in the list. I see this button and can click on it and then the request is sent fine. So in this form, it works, but I prefer to use the solution from react-admin
and don’t add this header manually. Is it possible?