I am trying to wrap my head around ReactJS and I am stumped with an issue where I want to be able to update the value of a local variable and return the updated value.
I've read about state and I've used that when working with React Components, however, this class is just defined as const and it doesn't extend React.Component.
Is there a different way I should be defining setting the variable?
Here is a simplified version of my code:
import React from 'react';
const WelcomeForm = ({welcome}) => {
var welcomeMsg = 'Test';
DynamicContentApi.loadDynamicContent('welcome_test').then((response) => {
// response.text has content
welcomeMsg = response.text;
}).catch(() => {
welcomeMsg = '';
});
return (
<p>{welcomeMsg}</p> // Returns 'Test'
);
};
export default WelcomeForm;
stateby extendingReact.component.DynamicContentApilogic above in the hierarchy and pass the result as a prop to this component.loadDynamicContentexecutes asynchronously, so by the time it completes, your component has already rendered with'Test'. And sincewelcomeMsgis just a local variable, it won't trigger a re-render when it changes (as it would if it were a prop or kept in state).