I am doing a simple exercise to clear my hook concept.
In my current scenario, I need to call the API
only if i click on the Call API
button and that time the page number should be the current value of Click Me
button value.
But currently, on every Click Me
button click the API is called.
I have tried with this solution, but can not get the result.
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
console.log(ref.current);
return ref.current;
};
export default function GetAPIData(props) {
const [chars, setChars] = useState([]);
const prevCount = usePrevious(props.id);
console.log(
"Previous value is: " + prevCount,
"Current value is: " + props.id
);
useEffect(() => {
axios
.get(`https://rickandmortyapi.com/api/character/?page=${props.id}`)
.then((res) => {
setChars(res.data.results);
})
.catch((err) => {
alert(err.message);
});
}, [prevCount, props.id]);
return (
<div className="container">
<h3>
<span>Achtung,</span> ein Trend geht um
</h3>
</div>
);
}
Here is the working Sandbox URL for reference.