1

I am new to the RTK Query and I use Redux ToolKit Query to fetch the data. Question: How do I dynamically change the baseUrl in createApi from the input field in App.js file.

I saw similar question here, but the solutions which was provided doesn't work in my case. How to dynamicly chane base URL using redux-toolkit?

export const WebApi = createApi({ 
    reducerPath: 'API',
    baseQuery: fetchBaseQuery({ baseUrl: 'http://localhost:3001/api' }),
    endpoints: () => ({}),
});

How to make API call from App.js file, where user can put any kind of API link in the input field and get the result.

something like this:

const dynamicUrl = ''
<button className="btn" type="button" onClick={() => refetch(dynamicUrl)}>Fetch Data</button>
Community
  • 1
  • 1
Coding Data
  • 13
  • 1
  • 3

2 Answers2

1

If you pass in a full url (starting with http:// or https://) fetchBaseQuery will skip baseUrl and use the supplied url instead. So you can use the logic that you linked above to just prepend your current baseUrl to the url of the query.

Noor Fahad
  • 94
  • 7
  • do you mean like this: > baseQuery: fetchBaseQuery({ base Url: '' }) – Coding Data Apr 01 '22 at 04:48
  • You can also leave out `baseQuery` completely, or have `baseQuery` pointing to `http://example.com` but have one endpoint go to `https://api-examples.org/foo/bar` instead. – phry Apr 01 '22 at 07:17
  • i'm trying to toggle between local (http://) and prod (https://) at runtime with an admin screen. these options seem to only allow change the URI the first time the `createApi` is called, not after that. Also the handling with http or https as a prefix is harder to do unless the whole API is dynamic. Is there a way to process each time the API call is made, to get the latest endpoint URI? – dcsan Sep 02 '22 at 21:56
1

You can just put "https://" in your baseUrl and for endpoints you can pass a string which will be your dynamic urlYou can do like this

export const WebApi = createApi({
   reducerPath: 'API',
  baseQuery: fetchBaseQuery({
    baseUrl: "https:",
  }),
  endpoints: (builder) => ({
    getUsers: builder.query({
      query: (name) => `/${name}`,
    }),
  }),
});

export const { useGetUsersQuery } = usersApi;

In your App.js you can just pass the value

const { data, isLoading, refetch } = useGetUsersQuery('//randomuser.me/api');

Hope it helps