Returning a variable from react functional component
20,595
Solution 1
You could get the code in componentDidMount
and store it in state instead.
Example
function doCall() {
return new Promise(resolve => setTimeout(() => resolve("code"), 1000));
}
class ModulesListing extends React.Component {
state = { code: null };
componentDidMount() {
this.getModuleCode();
}
getModuleCode = module => {
doCall(this.props.module).then(code => {
this.setState({ code });
});
};
render() {
const { code } = this.state;
if (code === null) {
return null;
}
return <div> {code} </div>;
}
}
ReactDOM.render(<ModulesListing />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Solution 2
Try calling a function in ComponentDidMount()
as
componentDidMount(){
this.getModuleCode(this.props.module);
}
and put moduleCode
in state so that you can receive it after it calls didmount
.
like
getModuleCode(module){
var moduleCode = 0;
// Do relevant calls and get moduleCode
this.setState({moduleCode});
}
receiving it in render - this.state.moduleCode
Related videos on Youtube
Author by
usergs
Updated on July 17, 2020Comments
-
usergs over 3 years
I have a react component as :
class ModulesListing extends React.Component { render(){ const module = this.props.module; getModuleCode(module){ var moduleCode = 0; // Do relevant calls and get moduleCode return moduleCode; } return ( //Info to display ); } }
Here, I need to get the value of moduleCode within return() and assign it to a variable to do further processing. when I assigned as,
var moduleCode = this.getModuleCode(module);
it returns an undefined object. What is the correct way of returning a value from a function?
-
Tholle over 5 years
const theCode = getModuleCode(module);
? -
Harikrishnan over 5 yearsthe problem is not clear
-
usergs over 5 years@Tholle sorry, edited question. Though, not working
-
usergs over 5 years@Harikrishnan, function getModuleCode() is returning an integer which needs to be used in render() method. How can I get that value and stored in a varible
-
-
usergs over 5 yearsIt works fine, there is another instance like I am getting list of modules as props. I need to run a loop to get moduleCode for each module within render. In that case which could be the feasible solution
-
Tholle over 5 years@usergs Great. That changes the question entirely. Please accept an answer to this question and create a new question if you have further issues. You could do something like this.
-
usergs over 5 yearsTried this way, when printed moduleCode in console, it says undefined