Reputation: 75
I am new to next.js. I want to pass page state to getServerSideProps. Is it possible to do this?
const Discover = (props) => {
const [page, setPage] = useState(1);
const [discoverResults, setDiscoverResults] = useState(props.data.results);
// console.log(discoverResults, page);
return (
<div>
<Card items={discoverResults} render={(discoverResults) => <DiscoverCard results={discoverResults} />} />
</div>
);
};
export default Discover;
export async function getServerSideProps() {
const movieData = await axios.get(`https://api.themoviedb.org/3/discover/movie?api_key=${process.env.NEXT_PUBLIC_MOVIE_DB_KEY}&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=${page}&with_watch_monetization_types=flatrate`);
return {
props: {
data: movieData.data,
},
};
}
Upvotes: 1
Views: 2687
Reputation: 476
I recommend to use SWR for handling this kind of api calls
an example of this here: https://swr.vercel.app/examples/ssr
In this example, it can be seen that the api calls happens in the Server side and it is being cached in the Client side.
For handling the query from the urls. This can be done using the same methods as well following the examples from their documentation of SWR https://swr.vercel.app/docs/pagination#pagination
SWR will help alot of stuffs in the api state management. I really recommend to start learning it as soon as possible..
Upvotes: 1
Reputation: 492
the only way is changing your route with params and recive it in server side :
import { useRouter } from "next/router";
const Discover = (props) => {
const { page } = props;
const router = useRouter();
const goToNextPage = () => {
router.replace(`/your-page-pathname?page=${+page + 1}`);
}
return (
<div>
page is : {page}
<button onClick={goToNextPage}>
next page
</button>
</div>
);
};
export default Discover;
export async function getServerSideProps(context) {
const { page } = context.query;
return {
props: {
page: page || 0,
},
};
}
To read more on the topic, recommend reading: Refreshing Server-Side Props
Upvotes: 2