Set a cookie in react to true all the time

306 Views Asked by At

I want to set a cookie to be on true all the time, not when something is happening or something is clicked.

So there are several tutorials and articles about that. In my case it should be something like: 'mySpecialCookie = true'.

Installing the package: npm install react-cookie

Does it need to be imported in both index.js and App.js?

My index.js looks like this:

import React from 'react';
import ReactDOM from 'react-dom';
import configureStore from './store/configureStore';
import getMiddlewares from './middlewares';
import App from './containers/App';
import * as serviceWorker from './serviceWorker';

const storeConfig = configureStore(getMiddlewares());

ReactDOM.render(
  <storeConfig.Provider store={storeConfig.store}>
    <App />
  </storeConfig.Provider>,
  document.getElementById('root')
);

serviceWorker.unregister();

So I assume that inside ReactDOM it should be changed to this?

import { CookiesProvider } from "react-cookie";
...
ReactDOM.render(
  <storeConfig.Provider store={storeConfig.store}>
    <CookiesProvider>
      <App />
    </CookiesProvider>
  </storeConfig.Provider>,
  document.getElementById('root')
);

And in App.js I added it using useCookies hooks but don't know where to use it:

import React, { useEffect } from 'react';
import { useCookies } from 'react-cookie'; //// <---   added it here 
import { IntlProvider } from 'react-intl';
import { useSelector, shallowEqual, useDispatch } from 'react-redux';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import Main from './Main';
import OrderDetails from './OrderDetails';
import { fetchDictionary } from '../actions/dictionary';
import { getLanguageCode } from '../utils';
import { HOME_PAGE, ORDER_DETAILS } from '../constants/routes';

const App = () => {
  const dictionary = useSelector((state) => state.dictionary, shallowEqual);
  const routes = [
    { path: HOME_PAGE, component: Main },
    { path: `${ORDER_DETAILS}/:id`, component: OrderDetails }
  ];
  const dispatch = useDispatch();

  const [mySpecialCookie, setMySpecialCookie] = useCookies(true);  //// <---   added it here 

  useEffect(() => {
    dispatch(fetchDictionary(getLanguageCode()));
  }, [dispatch]);

  return (
    <IntlProvider
      key={dictionary.locale}
      locale={dictionary.locale}
      messages={dictionary.messages}>
      <Router>
        {routes.map((route, index) => (
          <Route
            key={index}
            path={route.path}
            exact
            component={route.component}
          />
        ))}
      </Router>
    </IntlProvider>
  );
};

export default App;

Any suggestions?

1

There are 1 best solutions below

0
On

I have found a much shorter way to do it using js-cookie.

In the App.js file:

...
import Cookies from 'js-cookie';
...

const App = () => {
   ...
   Cookies.set('mySpecialCookie', true);
   ...
}