How to increase the value of a parameter by one in a URL
Problem Description:
I use Axios to get users. I get each user one at a time when the button is clicked. I need the ID parameter to increase by 1 when clicked. First it should be "…user/1", and then when clicked "…user/2" and so on. How can I do it?
const Button = () => {
const handleUser = () => {
axios.get(".../user/1/").then((res) => {
....
});
};
return <button onClick={handleUser}>NEXT</button>;
};
export default Button;
Solution – 1
Try this to increment the index of the call.
const Button = () => {
const [index, setIndex]=useState(0)
const increment = () => {
setIndex(i => i + 1)
}
const handleUser = () => {
increment()
axios.get(`.../user/${index}/`).then((res) => {
....
});
};
return <button onClick={handleUser}>NEXT</button>;
};
export default Button;
Solution – 2
I,
You need to store the current user id in a state (either directly in your Button component or in its parent component.
ex:
const Button = () => {
const [userId, setUserId] = useState(1);
const handleUser = () => {
axios.get(`.../user/${userId}/`).then((res) => {
....
}).finally(() => setUserId(userId => userId + 1));
};
return <button onClick={handleUser}>NEXT</button>;
};
export default Button;