Next.js Discord

Discord Forum

Tring to use Context Api but a TS error

Answered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
I am using next.js with TS so, i am tring to use Context api but a TS error:
this is my Context def:
"use client";

import { createContext, useState } from "react";

interface MyContextProps {
data?: {
artists: string;
song_name: string;
cover_url: string;
song_url: string;
};
setData?: (data: MyContextProps["data"]) => void;
}

export const MyContext = createContext<MyContextProps>({});

export default function MyProvider({
children,
}: {
children: React.ReactNode;
}) {
const [data, setData] = useState<MyContextProps["data"] | undefined>(
undefined
);

return (
<MyContext.Provider value={{ data, setData }}>
{children}
</MyContext.Provider>
);
}
if anyone can help!
Answered by ᴉuɐpɹɐɐ
you could do that as the intial value. Then you pass setData to the <MyContext.Provider values={}>
View full answer

4 Replies

@Cape lion I am using next.js with TS so, i am tring to use Context api but a TS error: this is my Context def: "use client"; import { createContext, useState } from "react"; interface MyContextProps { data?: { artists: string; song_name: string; cover_url: string; song_url: string; }; setData?: (data: MyContextProps["data"]) => void; } export const MyContext = createContext<MyContextProps>({}); export default function MyProvider({ children, }: { children: React.ReactNode; }) { const [data, setData] = useState<MyContextProps["data"] | undefined>( undefined ); return ( <MyContext.Provider value={{ data, setData }}> {children} </MyContext.Provider> ); } if anyone can help!
this is intentional. You could be using your context where its not wrapped with MyContext.Provider.

If you want to useContext to not work outside of MyContext.Provider then just throw an error like

const { data, setData } = useContext(MyContext); 
if(!data || !setData) throw new Error('The context is not wrapped under MyContext.Provider')


You can also make sure that the initial values for your context (at the createContext code) returns an empty function
Cape lionOP
no that is different. So if you see i have create a state using useState and accessing it (both the state i.e., data and its update function) now the setData has a return type of void | undefined because of that this error is showing.
@Cape lion so should I create a function where i have created MyProvide and then pass that function to update state rather passing setData.
you could do that as the intial value. Then you pass setData to the <MyContext.Provider values={}>
Answer