Home > Enterprise >  UseContext can't find variable?
UseContext can't find variable?

Time:12-28

I'm trying to understand useContext but I don't see what I'm doing wrong here, I get the error message "Can't find variable: Test" but in the tutorial I'm reading from it never says anything about needing to import/export other than what is in the code? Thank you!

App.js

    import React, { createContext } from 'react';
    const Test = createContext()

    export default function App() {
  return (
    <Test.Provider value="hello">
        <Home/>
    </Test.Provider>  );
}

Home.js

const Home = () => {

    return(
        <Test.Consumer>
                <View style={styles.homeContainer}>
                  {value}
                </View>
        </Test.Consumer>
    )
}

CodePudding user response:

You aren't exporting Test from App.js, so you can't just implicitly use it in Home.js.

I'd recommend moving it to another file, say, contexts.js:

import React from 'react';
const Test = React.createContext();
export {Test};

You can then do

import {Test} from './contexts';

in both (or all, in the future) of your other source files to refer to the same context type.

CodePudding user response:

I suggest you to create the context in a separate file :

test-context.js

import { createContext } from 'react';
export const TestContext = createContext();

App.js

import React from 'react';
import { TestContext } from './test-context';

export default function App() {
  return (
    <TestContext.Provider value="hello">
        <Home/>
    </TestContext.Provider>  
  );
}

In TestContext.Consumer, you must provide a function to consume the context value.

Home.js

import React from 'react';
import { TestContext } from './test-context';

export default const Home = () => {
  return (
    <TestContext.Consumer>
      value => (
        <View style={styles.homeContainer}>
          {value}
        </View>
      )
    </TestContext.Consumer>
  )
}

CodePudding user response:

We often forget about old school rules, when reading docs about fancy libraries these days.

In your example, Context is just a JS object, in order to access Test.Consumer, Test must be in scope of the file.

So, you have to import Test object (context) on order to access the Consumer property.

  • Related