Reputation: 137
In my Context.js file, I am passing multiple state variables:
return (
<Context.Provider value={[searchResult, setSearchResult, currentProduct, setCurrentProduct, apiKey, userId, setUserId]}>
{props.children}
</Context.Provider>
);
And in a specific component, I am using only the userId and setUserId elements. To receive these variables, I do:
let [searchResult, setSearchResult, currentProduct, setCurrentProduct, apiKey, userId, setUserId] = useContext(Context);
The question is: is there a way to receive only userId and setUserId in this component without having to declare all the other unused variables as well ?
Upvotes: 0
Views: 164
Reputation: 2112
You can change how you're passing the value from an array to an object.
return (
<Context.Provider value={{ searchResult, setSearchResult, currentProduct, setCurrentProduct, apiKey, userId, setUserId }}>
{props.children}
</Context.Provider>
);
let { userId, setUserId } = useContext(...)
If you don't want to change it, you can use the index but I wouldn't recommend it.
let context = useContext(...)
let userId = context[5]
let setUserId = context[6]
Upvotes: 2