How would I go about running this async with ReactJS?
{array.map((content, index) => {
const var = await asyncFunction(param)
return(
<div key={index} className="someClass">
<h4 className="anotherClass">{var}</h4>
</div>
)
})}
You have to separate the async processing from the rendering (as of React 17, at least), and you have to use the promise directly, but can be done in a function, stored in a state variable, then rendered. That function can be called when the array changes using useEffect.
Example:
function MyComponent(array) {
const [vars, setVars] = useState([]);
function handleArrayChanged(newArray) {
// note: no error handling, do this yourself as appropriate.
Promise.all(array.map(var => asyncFunction(var)))
.then((newVars) => setVars(newVars))
.catch(error => { /* handle error */ });
}
useEffect(() => {
handleArrayChanged(array);
}, [array]);
return (
<>
{vars.map((var, index) => {
return(
<div key={index} className="someClass">
<h4 className="anotherClass">{var}</h4>
</div>
)
})}
</>
}
Depending on exactly what asyncFunction does, you may want to break that async check out into its own component, as well, but that's subjective based on what asyncFunction does.
function MyComponent({element}) {
const [var, setVar] = useState(undefined)
function handleElementChanged(newElement) {
asyncFunction(newElement)
.then(newVar => setVar(newVar))
.catch(error => { /* handle error */ });
}
useEffect(() => {
handleElementChanged(element);
}, [element]);
return (
<div className="someClass">
<h4 className="anotherClass">{var}</h4>
</div>
);
}
function MyList({array}) {
return (
<>
{array.map(element, index) => (
<MyComponent
key={index}
element={element}
/>
)}
</>
);
}