Summary) How do you receive props from a parent component when your current child component is receiving only the data as props from getStaticProps?
For example, Todos component is a child component of a parent component and Todos needs to receive props from the parent. Since I am using getStaticProps to fetch data in the beginning of the app, the Todos component has props from getStaticProps only.
const Todos = ({ todos }) => {
return (
<div>
<ul>
{todos.length > 0 ? todos.map((todo) => <li>{todo}</li>) : "No todos"}
</ul>
</div>
);
};
export default Todos;
export async function getStaticProps() {
const todos = await fetch("https://.../todos");
return {
props: {
todos,
},
};
}
export default function Home({ currentUser, setCurrentUser }) {
return (
<div>
<Todos currentUser={currentUser} setCurrentUser={setCurrentUser}/>
</div>
);
}
//and then in Todos.js
const Todos = ({ props }) => {
...}
If I pass in props like above, if I console log the props in Todos component, I only see 'currentUser'. I don't see the props (todos) from the getStaticProps.
2.So I tried another way using Link but I could not figure out a way to pass down props, currentUser and setCurrentUser using Link..
export default function Home({ currentUser, setCurrentUser }) {
return (
<div>
<Link href="/Todos">
<a>Click to see Todos</a>
</Link>
</div>
);
}
What am I missing? Any help would be appreciated!
There is a rule which states that you can only use server site functions like getStaticProps()
or getServerSideProps()
in a page component so I assume that you have Home as a page component and you want use Todo Component inside Home Component. In effect, you should transfer getStaticProps() to Home Component:
export default function Home(props) {
return (
<div>
<Todos todos={props.todos} currentUser={props.currentUser} setCurrentUser={props.setCurrentUser}/>
</div>
);
}
export async function getStaticProps() {
const todos = await fetch("https://.../todos");
return {
props: {
todos,
},
};
}
In a nutshell; you should change your structure.