Reputation: 1464
I want to call three URLs and render their data from getServerSideProps()
, so I'm using axios.all([])
like this:
export async function getServerSideProps(ctx) {
const profileURL = 'http://localhost:8000/api/auth/profile/';
const bookmarkURL = 'http://localhost:8000/api/blogs/saved/';
const profileDataReq = axios({method: 'GET',
url: profileURL,
headers: ctx.req ? { cookie: ctx.req.headers.cookie } : undefined
});
const bookmarksReq = axios({method: 'GET',
url: bookmarkURL,
headers: ctx.req ? { cookie: ctx.req.headers.cookie } : undefined
});
const resp = await axios.all([profileDataReq, bookmarksReq]);
const data = axios.spread(function(profile, bookmark) {
console.log('My profile: ', Profile);
console.log('Saved blogs: ', saved);
})
return {
props: { }
};
};
My question is how do I return the axios
data from getServerSideProps()
's return{...}
so that I can use it in the component?
Upvotes: 2
Views: 4852
Reputation: 50308
I would suggest you use Promise.all
instead of axios.all
/axios.spread
(they've been deprecated) for this use case.
export async function getServerSideProps(ctx) {
const profileDataReq = axios({
method: 'GET',
url: 'http://localhost:8000/api/auth/profile/',
headers: { cookie: ctx.req.headers.cookie }
});
const bookmarksReq = axios({
method: 'GET',
url: 'http://localhost:8000/api/blogs/saved/',
headers: { cookie: ctx.req.headers.cookie }
});
const [profile, bookmarks] = await Promise.all([
profileDataReq,
bookmarksReq
]);
return {
props: {
profile: profile.data,
bookmarks: bookmarks.data
}
};
};
Also note that ctx.req
is always defined in getServerSideProps
.
Upvotes: 5