Dynamically Pass Component props in NextJs
I have a component Form like below -
const MyApp = ({ Component, pageProps, getReqCookie }) => {
const variable = Component.variable;
console.log(variable)
}
const Index = () => {
}
Index.variable = "something"
Currently passing static variable to MyApp like this. But how can I pass this variable dynamically to my MyApp?
the variable should load API data and pass it to MyApp Component.
Example:
Index.variable = {fetched data from api}
I used getserverSideprops and initialize the data inside it. But not working.
export const getServerSideProps = async () => {
const data = fetched from API
Index.variable = data;
}
Solution 1:
Next.js doesn't provide mechanism for attaching "dynamic data" to components. Probably because this approach presents several problems to solve. What data exactly should be fetched? When? By what component? One of the workarounds would be to attach data fetching function to the page:
Page.fetchData = async () => {
// fetch data from api
}
And then resolving it in _app.js:
const App = ({ Component, pageProps }) => {
const [fetchedData, setFetchedData] = useState();
useEffect(() => {
Component.fetchData().then((resolvedData) => {
setFetchedData(resolvedData);
});
}, [Component]);
// do something with fetchedData
};
On the other hand, did you consider just fetching this data inside page and pass it to components down the tree?