Reputation: 358
I am trying to pass a context object in NextJS which is using data from a useState hook, but the state variable and setState functions are undefined when consumed. This is strange since when I pass a simple variable in its place, it works fine, it is only when using useState that it is undefined. So I know the context object is working, but the useState hook is not.
My _app.js
file:
import React from 'react';
import App from 'next/app';
import Head from 'next/head';
import Aux from '../hoc/Aux';
import ContextProvider from '../context/context';
class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<Aux>
<Head>
<title>MyApp</title>
</Head>
<ContextProvider>
<Component {...pageProps} />
</ContextProvider>
</Aux>
);
};
};
export default MyApp;
My context.js
file:
import React, { createContext, useState } from 'react';
export const Context = createContext();
const ContextProvider = (props) => {
const [ activeTab, setActiveTab ] = useState('OVERVIEW');
return (
<Context.Provider value={{ activeTab, setActiveTab }}>
{props.children}
</Context.Provider>
);
};
export default ContextProvider;
My nav.js
file:
import styled from 'styled-components';
import { Context } from '../../context/context';
import { useContext } from 'react';
const Nav = () => {
const [activeTab, setActiveTab] = useContext(Context);
const TourNavUl = styled.ul`
`;
const TourNavLi = styled.li`
`;
return (
<NavUl>
<NavLi>
<span onClick={() => setActiveTab('OVERVIEW')}>Overview</span>
</NavLi>
<NavLi>
<span onClick={() => setActiveTab('ITINERARY')}>Itinerary</span>
</NavLi>
<NavLi>
<span onClick={() => setActiveTab('DETAILS')}>Details</span>
</NavLi>
<NavLi>
<span onClick={() => setActiveTab('BOOKINGS')}>Bookings</span>
</NavLi>
</NavUl>
);
};
export default Nav;
This is returning the error TypeError: setActiveTab is not a function
, because it is undefined. As I stated earlier, if I pass a simple variable through the context it works fine so I know it is set up correctly, but the state is not passing through the context object.
What am I doing wrong with the state?
Upvotes: 0
Views: 1592
Reputation: 865
useContext
is returning an object, not an array.
Instead of this
const [activeTab, setActiveTab] = useContext(Context);
Your should have this:
const {activeTab, setActiveTab} = useContext(Context);
Upvotes: 1