populated in getStaticProps
but undefined in export default
#17054
-
I read nextjs documentation and searched for a solution a lot in search engines. I expect to get a populated data in the exported function for this page. In I have made some changes in the getStaticPaths function also // pages/questions/[qid].js
async function fetchQuestion(qid){
const question = await axios.get("http://localhost:9000/api/questions/"+qid)
.then(response=>response.data)
.catch(err=>{
console.log("Error while fetching questions", err);
return null;
})
return question;
}
export async function getStaticPaths() {
return {
paths: [
{ params: { qid: '*' } } // I have made changes here
],
fallback: true // I have made changes here
};
}
export async function getStaticProps({params}){
const {qid} = params;
const question = await fetchQuestion(qid);
console.log("the data is ", question); // this is populated with actual data from backend
return {
props:{question}
}
}
function Qid(props) {
// props.question is alway undefined
const [loading,setLoading] = useState(true);
useEffect(()=>{
if(props.question)
setLoading(false);
},[props.question])
return (
<div>
{loading?
<p>Page is loading</p>
:
<>
<Question question={props.question}/>
<Editor/>
</>
}
</div>
);
}
export default Layout(Qid); I would be very grateful if this error could be pointed out. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
You This should fetch your data and then wait to respond until it is received. Your current code will return before the async function fetchQuestion(qid){
try {
const response = await axios.get("http://localhost:9000/api/questions/"+qid);
const question = response.data;
return question;
} catch(err) {
console.log("Error while fetching questions", err);
return null;
}
} |
Beta Was this translation helpful? Give feedback.
You
fetchQuestion
function is mixing async/await and.then
promise chaining.This should fetch your data and then wait to respond until it is received. Your current code will return before the
.then
is called.