Many people ask how to disable jquery ajax cache in React, while my question is different. I want it to be cached, or maybe more precisely, save the property I got from the first time call with ajax in browser memory or whatever, then it will not call the REST api again.
Below is my code:
import React from 'react';
import $ from 'jquery';
export default class ActivityIndex extends React.Component {
constructor(props) {
super(props);
this.state = {
activities: [],
};
}
componentDidMount() {
const source = 'http://api.my.com/activities';
this.serverRequest = $.get(source, (result) => {
this.setState({
activities: result,
});
});
}
componentWillUnmount() {
this.serverRequest.abort();
}
render() {
let rows = [];
this.state.activities.forEach((element) => {
rows.push(
<div key={element.act_id}>
<div>{element.act_id}</div>
<div>{element.act_title}</div>
</div>
);
});
return <div>{rows}</div>;
}
}
Every time I click back to this page, it will call the ajax again. I believe it's because in the componentDidMount method I called the ajax. Maybe I should put it in other place? Or how can I cache the ajax result, so then next time when I enter this page, the ajax will not be called?