'How do I hide the Next button when the last page is shown?
I am getting data from an API for a particular page using the below code:
const [ loading, setLoading ] = useState(true);
const [ showsData, setShowsData ] = useState(undefined);
const [ newData, setNewData ] = useState(undefined);
const [pageNumber, setPageNumber] = useState(props.match.params.pageno);
useEffect(() => {
async function fetchData() {
try {
const { data } = await axios.get('http://api.tvmaze.com/shows?page=' +pageNumber);
setShowsData(data);
setLoading(false);
} catch (e) {
console.log(e);
}
}
fetchData();
}, [ pageNumber ]);
Now, for pagination I am trying to hide the next button until the last page, I can get the last page by fetching data for the page after it. If it returns empty [], I will know that I found the last page and can hide the next button. To do this I created another useEffect:
useEffect(() => {
async function fetchData() {
try {
const { data } = await axios.get('http://api.tvmaze.com/shows?page=' +pageNumber+1);
setNewData(data);
setLoading(false);
} catch (e) {
console.log(e);
}
}
fetchData();
}, [ pageNumber ]);
To hide the next button I am doing the following:
{ newData!==[] && <Link className='showlink' to {`/shows/page/${parseInt(pageNumber)+1}`}>
Next
</Link>}
This does not work and the next button is shown even after the last page. How can I fix this?
Solution 1:[1]
Set initial state of newData to an empty Array.
const [ newData, setNewData ] = useState([]);
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 | Madhan S |
