1

In my pages/index.js there is getStaticProps function which fetches list of articles (I'm creating a blog website) which is then used as an init value of my useReducer that is located in the same file. I'm using useReducer to do some basic sorting and filtering on the client side. I want to slim down my index.js page as well as switch from prop drilling to context API by moving useReducer logic into new context provider file.

I tried to create two files inside context folder: articles-context.js and ArticlesProvider.js. In ArticlesProvider.js I put all useReducer logic, but I cannot figure how to pass data from index.js to ArticlesProvider.js and use that data as initial useReducer value in order to utilize context API in my articles component and display list of articles instantly after loading the page. Is it even possible to manage state like this or is there much better way, or should I just stay with state management in my index.js file?

index.js looks like this right now:

*recuder...*

const Home = ({ articles }) => {
  const [state, dispatch] = useReducer(reducer, {
    articlesList: articles,
    filterValue: '',
  });

*functions dispatching actions...*
}

*getStaticProps function*
granex
  • 11
  • 3

1 Answers1

0

The data returned by getStaticProps is passed as props to the page. And this same props is accessible in _app.js.
so from _app.js you can pass it to contextProvider :

export async function getStaticProps() {
  return {
    props: {
      articles: {} //
      toContextProvider: {first: "val1", second: "val2"}
    },
  };
}

Then in MyApp you can recieve the passed data :

export default function MyApp({ Component, pageProps }) {
  console.log(pageProps.toContextProvider);
 //...
}
Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38