Reputation: 1808
I am using react-cookie v2 in my react/redux app. To set a cookie you need to wrap the component in a HOC withCookies(component)
, then you can use this.props.cookies.set('first_cookie', someCookie);
to set a cookie.
However, i would like to set my cookies in a util file that all my components can use to set cookies. For example.
storageUtil.js
export const setToCookies = (key, value, options) => {
cookies.set(key, value, options);
};
This util file cannot be wrapped with withCookies
and therefore doesnt have the cookies directly.
I could pass in the cookies instance from the using component (setToCookies(cookiesInstance, key, value, options)
), but I would rather import a cookie instance in the util file if possible somehow.
This has to be a very common usecase (to handle cookies in a util file), i just cannot figure out the best approach for doing this.
Upvotes: 2
Views: 2564
Reputation: 1808
I will write the two methods i found to work when searching for a generic solution. If a better solution is provided i will change accepted answer.
Solution 1:
withCustomCookies.js
import React from 'react';
import { withCookies } from 'react-cookie';
export function withCustomCookies(Component) {
return (props) => {
// CookieComponent needs a capital letter bc of JSX
let ExtendedCookieComponent = withCookies(withEncapsulatedCookies(Component));
return (
<ExtendedCookieComponent
{...props} />
);
};
}
export function withEncapsulatedCookies(Component) {
return (props) => {
// Only expose our own cookies methods defined in this scope
const {
// Dont expose cookies in using component
cookies, // eslint-disable-line no-unused-vars
...cleanedProps
} = props;
function getFromCookies(key) {
// Stuff to always do when getting a cookie
return cookies.get(key);
}
function setToCookies(key, value, options) {
// Stuff to always do when setting a cookie
cookies.set(key, value, options);
}
return (
<Component
getFromCookies={getFromCookies}
setToCookies={setToCookies}
{...cleanedProps} /> // All Props except for cookies
);
};
}
Used as:
export default withCustomCookies(Component);
this.props.getFromCookies(COOKIE_NAME);
Solution 2:
Use a regular cookieUtils file and pass in the cookies:
cookieUtils.js
export const setToCookies = (cookies, key, value, options) => {
// Stuff to always do when setting a cookie
cookies.setCookie(key, value, options);
};
Use as:
withCookies(NameOfComponent)
).setToCookies(this.props.cookies, key, value, options);
Upvotes: 0