DEV Community

HREngCode
HREngCode

Posted on

Calling values of nested Context Data in React

I'm currently working on a project where I am trying register a user and then call the user_id data to register an employee. The user is taken in as an object in my contextData component located in my authContext.js file shown below:

const contextData = {
user,
token,
loginUser,
logoutUser,
registerUser,
isServerError,
};

The contextData is exported at the bottom of the authContext file as shown:

EmployeeContext.Provider value={contextData}>{children}</EmployeeContext.Provider

My problem is how to call the user values in my RegisterEmployee.js after importing the data from the authContext like so:
const { contextData, token } = useContext(AuthContext);

I'm pretty new to react so hopefully this makes sense. Can anyone give me some guidance on using the code I have currently?

TIA

Top comments (1)

Collapse
 
brogine profile image
Eric Brogin

I think you almost got it right.
When you consume the context, you receive what you passed as value for the provider.
In this case, your value is contextData, so either you use it as an object:

const contextData = useContext(AuthContext);
contextData.user // here you access the user via object
contextData.token // here you access the token associated

or you destructure it:
const { user, token } = useContext(AuthContext);
registerEmployee(user, token) // here you just use user or token or whatever you want