6. Connect React client app to Azure Function API

Change the local React app code to use the Azure Function API.

At this point in the article series, both the React client and the Azure Function API work both locally and remotely. The remote Azure Static Web Apps resource provides a proxy between the React client and API. The local environment needs the same proxy so the local React client and API can work together. Use the Static Web Apps CLI (SWA CLI) to provide the local proxied environment for your local app.

Run both the React and Functions development environments, provided by each framework, then use those app URLs with the SWA CLI to provide the proxy between the two.

Create parent proxied project

  1. In order to control both the React app and API projects, create a ./package.json file in the root of the project.

    npm init -y
    
  2. Install required dependencies to run package.json scripts:

    npm install concurrently azure-functions-core-tools@3 @azure/static-web-apps-cli --save-dev 
    
  3. Replace the current package.json file's scripts section with the following script entries:

    "scripts": {
      "start-api": "cd api && npm start",
      "start-app": "cd app && npm start",
      "start-dev": "concurrently \"npm:start-api\" \"npm:start-app\" ",
      "start-swa": "swa start http://localhost:3000 --api-location http://localhost:7071",
      "start": " npm run start-dev && npm run swa-up"
    }, 
    

    These scripts separate out the development server of each environment from the SWA CLI call to join those two environments.

    Script Purpose
    start-api Start local Azure Functions runtime.
    start-app Start React app's local runtime.
    start-dev Start both local runtimes.
    start-swa Start SWA across both apps. Use the http://locahost:4280 base URL to request the proxied app.
    start Start everything.

Start local app for full-stack app

The React client and the Azure Function API have separate local development servers.

  1. In order to debug both client and API at the same time, open two separate instances of VS Code.

  2. In one instance, open the ./app folder. In the second instance, open the ./api folder. In each project, open an integrated terminal and start the project:

    npm start
    

    When both the React app and the Function API have started correctly, continue to the next step.

    Partial screenshot of Windows desktop with two separate VS Code instances running.

  3. In one of the VS Code instances (it doesn't matter which instance), open a second integrated terminal, change to the root directory and start the proxy:

    cd .. && npm run start-swa
    
  4. For the rest of the article, use port 4280, http://locahost:4280/, when you want to use the React app.

    The React client is now available on both port 3000 and on port 4280 (with a proxy to the API).

Add an HTML form to the React app to use the Function API

In VS Code for the React app, find the ./src/App.tsx file and replace the entire file with the following code:

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {

  const [name, setName] = React.useState('');
  const [message, setMessage] = React.useState('');

  const getDataFromApi = async(e: any)=>{
    e.preventDefault();
    const data = await fetch(`/api/hello?name=${name}`);
    const json = await data.json();

    if (json.message){
      setMessage(json.message);
    }
  };

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Static Web App: React App with Azure Function API
        </p>
        <form id="form1" className="App-form" onSubmit={e => getDataFromApi(e)}>
          <div>
            <input 
              type="text" 
              id="name" 
              className="App-input" 
              placeholder="Name" 
              value={name} 
              onChange={e=>setName(e.target.value)} />
            <button type="submit" className="App-button">Submit</button>
          </div>
        </form>
        <div><h5>Message: {message} </h5></div>
      </header>
    </div>
  );
}

export default App;

Use your static web app in browser

  1. Return to the web browser for the React app, and use the new form to enter your name and pass that name to the Function API.

    Screenshot of web browser displaying React app form.

  2. The React app responds with the success message:

    Screenshot of web browser displaying React app form and API response.

Commit changes to source control

  1. Check the new app code into your local repo and push to the remote repo:

    git add . && git commit -m "hello swa cli" && git push origin main
    
  2. In a web browser, go back to your GitHub repo, and make sure the next build of your Action succeeds with these new changes. The actions URL should look like:

    https://github.com/YOUR-ACCOUNT/staticwebapp-with-api/actions
    
  3. In VS Code, in the Azure explorer, find your static web app, then right-click and select Browse site.

  4. The same React app, as your local version, should appear. The same form functionality as your local version should work, returning a message from the API.

    Your code now successfully works locally and remotely for an Azure Static Web App.

Next steps