Access to localStorage from createApi RTK on first page load

Viewed 287

I have a case where I need to read my .env file on page load and if there is a specific value then I dispatch that value in my store, where I have createApi => baseUrl needs to access to that value, or localStorage, in order to use it as making an api call, here is an example of my code:

App.tsx

    React.useEffect(() => {
    const myCustomEndpoint = window._env_.MYENDPOINT;
    if(myCustomEndpoint) {
      dispatch(setApiEndpoint(myCustomEndpoint));
    }
}, [])

src/redux/reducerSlice.ts

export const reducerSlice = createSlice({
//...more slices
   setApiEndpoint: (state, action: PayloadAction<string>) => {
      state.apiEndpoint = action.payload;
      localStorage.removeItem('api');
      localStorage.setItem('api', state.apiEndpoint);
    }
})

src/services/api.ts

const baseUrl = localStorage.getItem(config.apiEndpoint) || '';
export const dataApis = createApi({
  reducerPath: 'dataApis',
  baseQuery: fetchBaseQuery({ baseUrl }), // here I cannot get the API for first time the page load
endpoints: (builder) => ({
 // my endpoints
})

So is there a way how to access the localStorage of the api endpoint which I have set for the first time my app was loaded?

1 Answers

I think you can set the endpoint directly in the createApi method, so just use like this for example: fetchBaseQuery({ baseUrl: window._env_.MYENDPOINT || '' }).

Related