Home > OS >  useContext returning undefined even with default values
useContext returning undefined even with default values

Time:11-07

useContext keeps returning undefined for me.

I am pretty confused as to why here as I have my Provider and I have my defaultValues.

Where I am consuming the context:

import React from 'react';
import { useContext } from 'react';
import { UserContext } from '../context/UserContext.js';

const Login = () => {
  console.log(UserContext);
  console.log(useContext(UserContext));
  const context = useContext(UserContext);

  const authenticate = (e) => {
    e.preventDefault();
    // const token = login();
    test();
  };

  return (
    <div className="login-container">
      <button onClick={authenticate}>Login</button>
    </div>
  );
}

export default Login;

my App.js:

import { UserProvider } from './context/UserContext.js';

import './App.css';


function App() {
  return (
    <UserProvider>
      <Login />
      </UserProvider>
  );
}

export default App;

my UserContext.js:

import { createContext } from 'react';
import Web3 from 'web3';
import APIClient from '../client/dapp-api';

const defaultValues = {
  user : null,
  test: () => {},
};

export const UserContext = createContext(defaultValues);


export const UserProvider = ({ children }) => {
  const test = () => {
    console.log('this works');
  };

  return(
    <UserContext.Provider values={{
      ...defaultValues,
      test,
      login,
    }}>
      { children }
      </UserContext.Provider>
  );
}

CodePudding user response:

Context providers have a prop named "value", not "values". In your UserProvider component, change your usage to:

<UserContext.Provider value={{ ...data here... }}>
  • Related