5

I am trying to figure out how I can get an ApiUrl setting from my AppSettings.json into my ReactJS / Redux state.

I have found the following article, however, it is for Angular. https://elanderson.net/2017/10/pass-asp-net-core-appsettings-values-to-angular/

I was able to use the example to alter my MVC page to this:

@using Microsoft.Extensions.Configuration @inject IConfiguration Configuration @{ ViewData["Title"] = "Home Page"; }

<div id="react-app" asp-prerender-module="ClientApp/dist/main-server" asp-prerender-data='new { apiUrl = Configuration["ApiUrl"] }'>Loading...</div>

@section scripts {
<script src="~/dist/main-client.js" asp-append-version="true"></script>
}

Here is my AppSettings.json:

{
  "ApiUrl": "http://localhost:55556/",
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

I want to send the ApiUrl parameter from my AppSettings to the ApplicationState and access it from my ReactJS TypeScript components.

I created this app with the command dotnet new reactredux and I am very new to ReactJS and Redux.

2 Answers 2

2

It took a bit to figure out but here is the solution.

  1. If you have not created a Reducer for Redux to store generic app settings create one. Here is my Reducer:

import {
  Action,
  Reducer
} from 'redux';

// -----------------
// STATE - This defines the type of data maintained in the Redux store.

export interface AppSettingsState {
  ApiUrl: string
}

// -----------------
// ACTIONS - These are serializable (hence replayable) descriptions of state transitions.
// They do not themselves have any side-effects; they just describe something that is going to happen.
// Use @typeName and isActionType for type detection that works even after serialization/deserialization.

export interface SetApiUrlAction {
  type: 'SET_APIURL';
  apiUrl: string
}

// Declare a 'discriminated union' type. This guarantees that all references to 'type' properties contain one of the
// declared type strings (and not any other arbitrary string).
type KnownAction = SetApiUrlAction;

// ----------------
// ACTION CREATORS - These are functions exposed to UI components that will trigger a state transition.
// They don't directly mutate state, but they can have external side-effects (such as loading data).

export const actionCreators = {
  setApiUrl: (url: string) => < SetApiUrlAction > {
    type: 'SET_APIURL',
    apiUrl: url
  }
};

// ----------------
// REDUCER - For a given state and action, returns the new state. To support time travel, this must not mutate the old state.

export const reducer: Reducer < AppSettingsState > = (state: AppSettingsState, incomingAction: Action) => {
  const action = incomingAction as KnownAction;

  switch (action.type) {
    case 'SET_APIURL':
      return {
        ApiUrl: action.apiUrl
      };
    default:
      // The following line guarantees that every action in the KnownAction union has been covered by a case above
      const exhaustiveCheck: never = action.type;
  }

  // For unrecognized actions (or in cases where actions have no effect), must return the existing state
  //  (or default initial state if none was supplied)
  return state || {
    ApiUrl: "http://localhost:5001/"
  };
};

  1. After Creating the reducer and hooking it into the allReducers list you need to edit boot-server.tsx. After boot-server creates the state you can dispatch anything you need to. Here I grab the data from the asp-prerender-data tag I set in my MVC view.

store.dispatch({ type: 'SET_APIURL', apiUrl: params.data.apiUrl });

Sign up to request clarification or add additional context in comments.

Comments

0

This other answer worked for me, I just had to add a const service class that would read this values How to push configuration values from Asp.Net Core MVC 2.0 config file to React TypeScript client script?

class ConfigService {
    Uri: string;

    public initialize(): void {
        if (this.Uri) return;
        var ell = document.getElementById('site-props');
        var jsontext = ell!.innerText;
        var siteProps = JSON.parse(jsontext);
        this.Uri = siteProps.Uri;
    } 
}

const configService = new ConfigService();
export default configService;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.