1

I'm working in a simple POC to learn how to connect React-Visualforce-Apex. I have success inserting data generated in a React form to Salesforce, but now I would like to retrieve Salesforce data on demand and display it in my React component hosted in Visualforce.

What I did:

  1. Created a VF page
  2. Hosted my React app for testing using a script and exposing my localhost as recommended here https://rajaraodv.medium.com/developing-react-redux-apps-in-salesforce-s-visualforce-3ad7be560d1c
  3. Called a remote Apex method using "Visualforce Remoting", successfully querying my data (just a list of fake leads).

Question:

How do I pass my returns back to the React component?

Visualforce page

<apex:page showHeader="false" sidebar="false" standardStylesheets="false" applyBodyTag="false" applyHtmlTag="false" controller="PreApp_Controller">
<script type="text/javascript">
    let allLeads = [];
    function getLeads() {
        Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.PreApp_Controller.getLeads}', handleResult);
    }

    function handleResult(result, event) {            
        this.allLeads = result;           
    }
</script>
<html>
<body>
    <div id="root">
       <script src="MY_REACT_APP_URL" />
    </div>
</body>
</html>
</apex:page>

My React App

import React from "react";
import { Button } from "@material-ui/core";
export default function Leads() {
   let leads = () => {
   getLeads();
};

return (
<>
  <Button
    color="primary"
    variant="contained"
    onClick={() => leads()}
    style={{ margin: 10 }}
  >
    Get Leads
  </Button>

  <ul>
    {allLeads.map((lead) => (
      <li>{lead.LastName}</li>
    ))}
  </ul>
</>
);
}

1 Answer 1

1

Whenever you need to call the server, you need a Promise, so:

function getLeads() {
  return new Promise((resolve, reject) => {
    try {
      Visualforce.remoting.Manager.invokeAction(
        "{!$RemoteAction.PreApp_Controller.getLeads}",
        resolve
      );
    } catch(e) {
      reject(e);
    }
  });
}

And in your React code:

export default async function leads() {
   const allLeads = await getLeads();
   this.setState({ allLeads });
};

I'm not an expert at React, so you might need some additional work, but this syntax should be pretty close.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.