The contextAPI is returning a state that is undefined

Currently, I am implementing contextAPI along with useState, where the initial value is an Object containing Themes.

However, when I try to log this in the console, it returns undefined.

export interface ITheme {
  themeMode: DefaultTheme
  setThemeMode: Dispatch<SetStateAction<DefaultTheme>>
}
interface IThemeProviderProps {
  children: ReactNode
}

const initialValues: ITheme = {
  themeMode: themesSchema.light,
  setThemeMode: () => null
}

export const ToggleThemeContext = createContext<ITheme>({} as ITheme)

export function ToggleThemeContextProvider({ children }: IThemeProviderProps) {
  const deviceTheme = useColorScheme()
  const firstThemeChoice = themesSchema[deviceTheme ? deviceTheme : 'light']
  
  const [themeMode, setThemeMode] = useState<DefaultTheme>(firstThemeChoice)
 
  const value = {
    themeMode, 
    setThemeMode
  }

  return (
    <ToggleThemeContext.Provider value={value}>
      {children}
    </ToggleThemeContext.Provider>
  )
}

I have also created a custom hook for accessing this functionality:

export function useToggleTheme(): ITheme {
  const context = useContext(ToggleThemeContext)
  //In using this hook, remember to pass in the setThemeMode(example)
  //where example -----> const example = colorScheme['light' | 'dark']
  return context
}

In my App, I utilized a provider. However, encountering issues because I need to utilize ThemeProvider from styled-components:

const { themeMode } = useToggleTheme()
console.log(themeMode) //Undefined

This is a snippet of my App:

export default function App() {
 
  const { themeMode } = useToggleTheme()
  return (
    <HeaderContextProvider>
      <ToggleThemeContextProvider> 
        <ThemeProvider theme={themeMode}>
          <SafeAreaProvider>
            {fontsLoaded ? <Routes /> : <Loading />}
            <StatusBar style="auto" backgroundColor="transparent" translucent />
          </SafeAreaProvider>
        </ThemeProvider>
      </ToggleThemeContextProvider>
    </HeaderContextProvider>
  )
}

Initially, I tried setting InitialValues in createContext. However, upon using setThemeMode, it does not work. This issue persists in other contexts that simply return undefined with boolean values as well when setXXX is used to update the state.

Answer №1

I found a solution to the issue...

It seems that we are unable to directly access values from the Provider inside the App.tsx file. To achieve this, it is necessary to utilize the Consumer instead...

In my case, I established a context related to theme colors called About and applied it to the ThemeProvider component in styled components...

By utilizing Context.Consumer, everything functions smoothly

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting the default value in setState in React Native allows you to initialize state

const fetchData = async (key) => { try { const jsonData = await AsyncStorage.getItem(key) return jsonData != null ? JSON.parse(jsonData) : false; } catch(error) { console.log(error); } } useEffect ...

What is the best way to implement bypassSecurityTrustResourceUrl for all elements within an array?

My challenge is dealing with an array of Google Map Embed API URLs. As I iterate over each item, I need to bind them to the source of an iFrame. I have a solution in mind: constructor(private sanitizer: DomSanitizationService) { this.url = sanitizer. ...

Create a React Native layout with a set width and the ability to stretch to fill

Is there a way to achieve this layout in react-native? I am looking to have a component with a fixed width on the right side, while another component on the left side takes up the remaining space. https://i.sstatic.net/3c6q6.png ...

"Unindexing data in Angular: A step-by-step guide

Can someone help me figure out how to delete an item by index in Angular? I have a parameter and a remove button, but when I tried putting my parameter inside the remove button it didn't work. How can I fix this? deleteRowFiles(rowIndex: number){ th ...

Challenges with implementing speech recognition within a React component's state

I've encountered an issue with the React library react-speech-recognition. When trying to modify the newContent state within useEffect, it ends up printing as undefined. Additionally, I'm facing a similar problem when attempting to update the sta ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Webpack may suggest, "An extra loader might be needed" within a React.js project

I recently created a React project with two separate workspaces, named 'webmail' and 'component'. In the 'component' workspace, I added a small tsx file that I wanted to utilize in the 'webmail' workspace. Below is t ...

Encountering a 'SyntaxError: Unexpected string' error close to the import statement while using ts-node-dev

Struggling to incorporate TypeScript libraries with Node, I keep encountering SyntaxErrors. When running the dev script from package.json using ts-node-dev, the errors tend to appear near the import statements. Unsure if it's an issue with my tsconfig ...

What is the most effective way to handle DOM events in Angular 8?

Looking to listen for the 'storage' event from the window in Angular 8. What is the recommended approach to achieving this in Angular? window.addEventListener('storage', () => { }); One method involves using Renderer2, but are ther ...

Can you explain how the "reduce" function can be implemented using an interface in TypeScript?

Can you explain the "reduce" function using an interface in TypeScript? https://i.stack.imgur.com/X1VxL.png ...

Issue encountered while attempting to run app.css file downloaded from Nativescript Playground

Encountering an error with my code... ERROR in ./app.css Module not found: Error: Can't resolve './nativescript-theme-core/css/core.light.css' in 'C:\Users\elish_n8zkzh8\Downloads\bandz test\app' @ ./app. ...

When importing a React Component with styling into the pages folder, it fails to function properly

I created a component in my components directory with custom styling: // import Link from "next/link"; import {Link} from "react-scroll" export default function Navbar() { return ( <div className="fixed w-full h-[79px] fle ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

Page Breaks - Patience in anticipation of dataSource readiness

I am facing an issue with my pagination service and component. The dataSource appears empty when the page is loaded for the first time, but by the second time it is populated and I can display the dataTable and paginate successfully. Is there a workaround ...

How to dynamically load components in Angular using *ngIf, template variables, and loadIntoLocation

I am currently working on developing a login page where the login template is dynamically replaced with the app+router-outlet. The HTML: <div class="contentWrapper" *ngIf="!logedin"> Login html.... </div> <div *ngIf="logedin"> ...

"I am facing issues with Nodejs $lookup as it is not producing the

I am looking to merge two document collections. The first collection, "prefix," contains an array of category IDs under the categoryId key, while the second collection, "categories," holds objects with a unique _id field. Here is my sample database structu ...

Tips for utilizing URL parameters within the useEffect hook

In my functional component, I am attempting to retrieve URL parameters that have been namespaced in react-router using a hook. useEffect(() => { document.title = props.match.params.subject UserServices.getSubject(props.match.params.subject) ...

What specific data type is required for the following code in Angular?

const componentMapper = { input: InputComponent, button: ButtonComponent, select: SelectComponent, date: DateComponent, radiobutton: RadiobuttonComponent, checkbox: CheckboxComponent, switch: SwitchComponent, textarea: TextAreaComponent }; ...

Async/await is restricted when utilizing serverActions within the Client component in next.js

Attempting to implement an infinite scroll feature in next.js, I am working on invoking my serverAction to load more data by using async/await to handle the API call and retrieve the response. Encountering an issue: "async/await is not yet supported ...