On index.js page I am fetching data that I would like all my pages has access to, but also depending on the data I receive, I want to redirect. How to redirect and pass data at the same time?
My code on _app.js
import "styles/globals.css";
import React from "react";
import axios from "axios";
import getServiceAddress from "service/get-service-address";
import Router from "next/router";
export const MyContext= React.createContext({});
function MyApp({ Component, pageProps, data, redirect }) {
return (
<MyContext.Provider value={data}>
<Component {...pageProps} />
</MyContext.Provider>
);
}
MyApp.getInitialProps = async (context) => {
if (context.ctx.pathname !== "/") { //if not index then do nothing
return {};
}
const id= context.ctx.query.id;
try {
const url = `http://somepage.com/${id}`;
const res = await axios.get(url);
const data = res.data;
if (data.hasSomeValue) {
/// I want to redirect and send the data
return {
data: data,
redirect: "/success",
};
}
return { data };
} catch (e) {
return {
redirect: "/error",
};
}
};
export default MyApp;