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:
- Created a VF page
- 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
- 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>
</>
);
}