简体   繁体   中英

How prevent calling same api in different components in react js

I am working large reactjs application,In that application so many components are there and so many api services also there. My problem is how to prevent calling same api in different components. Actually i want to call api one time then,i will use that api response entire application,so that we can prevent calling same api in different components. So please give me any solution. check the below demo code:

enter code here

`FirstComponent:
 ——————————————
 Class FirstComponent extends Component {
 constructor(props){
 this.setState={}
}
componentDidMount() {
this.props.dispatch(getById(1)); //here first time I am calling api
}
render(){
return(
———HTML Code HERE———
)
}
const mapStateToProps = state => {
  return {
    registrationData: state.RegistrationDemand.registrationData 
    // here I am getting response through redux reducer store
    };
};
export default compose(
  translate,
  withRouter,
  connect(mapStateToProps)
)(FirstComponent);

SecondComponent:
——————————————
Class SecondComponent extends Component {
constructor(props){
this.setState={}
}
componentDidMount() {
this.props.dispatch(getById(1));   //here I need to prevent this second time api calling
}
render(){
return(
———HTML Code HERE———
)
}
const mapStateToProps = state => {
  return {
    registrationData: state.RegistrationDemand.registrationData 
//without calling second component,If I use this one first time when I redirect to this page data is coming hereabout when I refresh second time it is getting null.
    };
};
export default compose(
  translate,
  withRouter,
  connect(mapStateToProps)
)(SecondComponent);`

You can actually call the API once your application is mounted. Usually this is done via componentDidMount or if you're using hooks, you can add it inside useEffect .

And you can just pass down props.

A more better solution is to use redux to your project, wherein the whole state of your application is inside a store in which you can connect using react-redux .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM