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.
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:
Used as:
export default withCustomCookies(Component);
this.props.getFromCookies(COOKIE_NAME);
Solution 2:
Use a regular cookieUtils file and pass in the cookies:
Use as:
withCookies(NameOfComponent)
).setToCookies(this.props.cookies, key, value, options);