2

I'm trying to set up useContext in the simplest way possible, but it keeps returning undefined.

I've checked it several times but still can't decipher what I'm missing.

Context.js:

import React from 'react';

export const Context = React.createContext();

export function Provider(props) {

    const sayHi = () => {
        console.log('hi')
    }

    const value = {
        actions: {
            sayHi
        }
    }

    return(
        <Context.Provider value={value}>
            {props.children}
        </Context.Provider>
    );
}

Consumer component (Transfer.js):

import React, { useContext } from 'react';
import { Context } from '../Context';

function Transfer() {
    const value = useContext(Context);
    console.log(value); // ------> returns undefined
    console.log(Context); // ----> it is defined

    return (
        <div className="send">
            // some HTML
        </div>
    );
}


export default Transfer;

Folder structure:

src
└───components
│   └─── Transfer.js
│  
└───App.js
└───App.scss
└───Context.js
    ...
dNyrM
  • 545
  • 1
  • 4
  • 17

2 Answers2

3

Answer: Missing Provider on root component

dNyrM
  • 545
  • 1
  • 4
  • 17
2

Hi @cdgmachado : The issue is due to an empty value when you're creating context value instead use this :
export const Context = React.createContext(null) This where i've read about it . https://kentcdodds.com/blog/how-to-use-react-context-effectively . You can look my codesandbox also : https://codesandbox.io/s/goofy-bash-z1cnq?file=/src/Context.js:28-76

From the blog : This a capture of the part talking about :

enter image description here

Hope that it'll solve it

dickosmad
  • 71
  • 1
  • 3