'React - Axios call make too many requests
Im learning React & Redux by making a game project. I want to fetch data (attributes) by API, but it cause too many requests. Guess it can be realted to placing axios call directly in functional react component, but i have no idea how to fix it.
function Attributes({ attributes, dispatch }) {
axios.get(`/api/heroes/1/get-attributes`).then(res => {
dispatch(AttribAction.set(objectToArray(res.data)));
});
return (
<div className="content">
{attributes.map((attrib, index) => (
<div
key={index}
className={attrib.id == null ? "attrib-block empty" : "attrib-block"}
>
<p>
<strong>{attrib.name}</strong>: {attrib.value}
</p>
<div>
<button
className="attrib-button"
onClick={() => dispatch(AttribAction.increment(attrib.id))}
>
+
</button>
<button
className="attrib-button"
onClick={() => dispatch(AttribAction.decrement(attrib.id))}
>
-
</button>
</div>
</div>
))}
</div>
);
}
Solution 1:[1]
You can use a useEffect
hook to run the data fetching.
Passing an empty array as the dependencies means the effect will run only once.
import React, { useEffect } from 'react';
function Attributes({ attributes, dispatch }){
useEffect(() => {
axios.get(`/api/heroes/1/get-attributes`)
.then(res => {
dispatch(AttribAction.set(objectToArray(res.data)));
});
}, [])
return(
<div className="content">
{attributes.map((attrib, index) =>
<div key={index} className={attrib.id == null ? "attrib-block empty" : "attrib-block"}>
<p><strong>{attrib.name}</strong>: {attrib.value}</p>
<div>
<button className="attrib-button" onClick={() => dispatch(AttribAction.increment(attrib.id))}>+</button>
<button className="attrib-button" onClick={() => dispatch(AttribAction.decrement(attrib.id))}>-</button>
</div>
</div>
)}
</div>
);
}
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 | Steve Holgado |