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>
);
}
Put the code in a useEffect hook, and then pass in an array as the second parameter to specify what variables should cause it to repeat the effect if they change. An empty array says never to repeat it.
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)));
});
}, []);
// ... etc
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With