Im building an app with NextJS. My app displays a list of post and the user has the ability to sort the list from A-Z or Z-A and to display a specific amount of posts per page (10,20,etc). When the user clicks on a post to visit that specific post page and then go back to the main list, the sorting and pagination preferences were getting reset, I managed to keep the preserved the values using cookies, but I would like to use useContext()
instead.
For this app I have a Layout.js
file, and thought that would be the right place to insert my Provider
like this:
import React, {useState} from 'react';
import Navbar from './Navbar';
import Head from 'next/head';
import {SortingContext} from './UseContext';
const Layout = (props)=> {
const [value, setValue] = useState('hello');
return (<SortingContext.Provider value={{value, setValue}}>
<div>
<Head>
<title>MyApp</title>
</Head>
<Navbar/>
{props.children}
</div>
</SortingContext.Provider>
)};
But when I try to get the value from one of my pages, I get TypeError: Cannot read property 'value' of null
I'm using useContext
somewhere else in my app, so I know I can get it to work. I just don't understand where to put it in my NextJS app, so the value will persist even if I visit a different page.
This is my index.js where I'm trying to print the value:
import React, { useState, useEffect, useContext } from 'react';
import withData from '../lib/apollo';
import Layout from '../components/Layout';
import {SortingContext} from '../components/UseContext';
import Footer from '../components/Footer';
const Home = () => {
const {value, setValue} = useContext(SortingContext);
return (
<Layout>
<div className='main_screen'>
<h1>{value}</h1>
</div>
{siteOptions && <Footer />}
</Layout>
)
};
export default withData(Home);
And my UseContext.js:
import {createContext} from 'react';
export const SortingContext = createContext(null);