Search code examples
javascriptreactjsreact-contextuse-context

Passing value by using Context API and useContext (React js)


I want to pass value of customerFlag which i have declared in Login.jsx component and want to access that value in Header.jsx. I am using Context API and useContext. Basically here i am passing value between two components you can say sibling components. but problem is i am getting customerFlag value is undefined under the UserContext.Provider value={customerFlag} tag. Kindly correct me if i am doing it wrong. I am a beginner in react js.

Login.jsx

import React, { createContext } from 'react';

      //Creating Context API
        const UserContext = createContext(null);
        .
        .
        .
        } else {
    
                 customerFlag='customer';
                 window.alert('Login successfull');
                 history.push('/home');
    
                }

return (
        <>
            
            {/* Providing the context to Header*/}

            <UserContext.Provider value={customerFlag} >
                <Header />
            </UserContext.Provider>

        </>
        )

Header.jsx

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

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

return ();
}

Solution

  • customerFlag='customer'; is not known in lifecycle of React component. It means if customerFlag changes later, your Context won't notice.

    You'll need to use state for customer flag. e.g.:

    const [cusomterFlag, setCustomerFlag] = useState('');
    
    // ...
    
    if(...) {
      // ...
    } else {
      setCustomerFlag('customer');
      window.alert('Login successfull');
      history.push('/home');
    }