I'm working with an API in Next.js and I'm trying to make a back/next button functional. With my code though, I'm getting a "res is not defined". How do I properly use conditionals with an await fetch request?
const Page = () => {
const [page, setPage] = useState(1);
const [data, setData] = useState(null);
const fetchContent = async (button) => {
if (button === "back" && page > 1) {
const res = await fetch(
`http://api-page.com/content/pagination[page]=${page}`
);
setPage(page - 1);
} else if (button === "next") {
const res = await fetch(
`http://api-page.com/content/pagination[page]=${page}`
);
setPage(page + 1);
} else {
const res = await fetch(
`http://api-page.com/content/pagination[page]=${page}`
);
}
const data = await res.json();
setData(data.data);
};
useEffect(() => {
fetchContent();
}, []);
return (
<div>
<button
onClick={() => {
fetchContent("back");
}}
>
Prev page
</button>
<button
onClick={() => {
fetchContent("next");
}}
>
Next page
</button>
);
};
export default Page;