'Fetch axios call only one time when render page
What is the best way to call the REST API in the Ionic React application. I want to be run only once when the component first loads. It's requested to server again when go to next page and back again to same page. I want to reduce api call if same page call again.
function Projects() {
const [projects, setProjects] = useState([]);
const [message, setMessage] = useState("");
React.useEffect(() => {
getProjects();
}, []);
const getProjects = async () => {
return api
.getprojects()
.then((response) => {
if (response.data.status) {
setProjects(response.data.data);
}
})
.catch((error) => {
setMessage(error);
});
};
return (
<IonPage>
<IonContent>
<div>
{projects.map(({ item, index }) => {
return (
<div key={index}>
<strong>{item.title}</strong>
</div>
);
})}
</div>
</IonContent>
</IonPage>
);
}
export default Projects;
Solution 1:[1]
You need to hold your projects state in a parent component. Global state can be managed with useContext, but that is a little advanced.
For your example, the simplest way would be to hold the state in your parent component and pass projects in as props to the Projects component.
Something like this:
const ParentComponent = () => {
const [projects, setProjects] = useState([]);
React.useEffect(() => {
projects.length === 0 && getProjects();
}, []);
const getProjects = async () => {
return api
.getprojects()
.then((response) => {
if (response.data.status) {
setProjects(response.data.data);
}
})
.catch((error) => {
setMessage(error);
});
};
return (
<Projects projects={projects}/>
)
}
And in Projects, remove that code:
function Projects({ projects }) {
const [message, setMessage] = useState("");
return (
<IonPage>
<IonContent>
<div>
{projects.map(({ item, index }) => {
return (
<div key={index}>
<strong>{item.title}</strong>
</div>
);
})}
</div>
</IonContent>
</IonPage>
);
}
export default Projects;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PsiKai |
