最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Integrating react-cookie with react redux - Stack Overflow

matteradmin4PV0评论

My main application is based on this old boilerplate which I have been slowly updating. Currently, all of the dependencies have been updated except for react-cookie.

I am trying to upgrade react-cookie to version 3.0.4 using this tutorial but I need some help overing some challenges I am facing during the transition process.

Following the tutorial, I changed index.js to

ReactDOM.render(
  <CookiesProvider>
    <Provider store={store}>
      <App />
    </Provider>
  </CookiesProvider>,
  document.querySelector('.wrapper'));

Now, my app.js file looks like this:

import React, { Component } from 'react'
import { withCookies } from 'react-cookie'
import Routes from '../Routes'

class App extends Component {
  render() {
    return (
      <div className="container">
        <Routes cookies={this.props.cookies} />
      </div>
    );
  }
}

export default withCookies(App)

Now, my biggest concern es here. My Routes ponent was never meant to be a Redux container so I changed it to this to acmodate the tutorial:

import React from 'react'
import { connect } from 'react-redux'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import ScrollUpButton from 'react-scroll-up-button'

// Import miscellaneous routes and other requirements
import NotFoundPage from './ponents/pages/not-found-page'

// Import Header and footer
import HeaderTemplate from './ponents/template/header'
import FooterTemplate from './ponents/template/footer'

// Import static pages
import HomePage from './ponents/pages/home-page'

// Import authentication related pages
import Register from './ponents/auth/register'
import Login from './ponents/auth/login'
import Logout from './ponents/auth/logout'
import ForgotPassword from './ponents/auth/forgot_password'
import ResetPassword from './ponents/auth/reset_password'
import ConfirmationMessage from './ponents/auth/confirmation_message'
import ResendVerificationEmail from './ponents/auth/resend_verification_email'

// Import dashboard pages
import Dashboard from './ponents/dashboard/dashboard'
import ChangePassword from './ponents/dashboard/profile/change-password'

// Import simulator pages
import Simulator from './ponents/simulator/index'

// Import higher order ponents
import RequireAuth from './ponents/auth/require_auth'

const BrowserRoutes = () => (
  <BrowserRouter>
    <div>
      <HeaderTemplate logo="Stress Path Simulator" />
      <Switch>
        <Route exact path="/" ponent={HomePage} />
        <Route exact path="/register" ponent={Register} />
        <Route exact path="/login" ponent={Login} />
        <Route exact path="/logout" ponent={Logout} />
        <Route exact path="/forgot-password" ponent={ForgotPassword} />
        <Route exact path="/reset-password/:resetToken" ponent={ResetPassword} />
        <Route exact path="/confirmation-message"  render={() => <ConfirmationMessage message="Please click on the link we sent to your email to verify your account." /> } />
        <Route exact path="/resend-verification-email" ponent={ResendVerificationEmail} />
        <Route exact path="/profile/change-password" ponent={RequireAuth(ChangePassword)} />
        <Route exact path="/confirmation-password-changed" render={() => RequireAuth(<ConfirmationMessage message="Password has been successfully changed!" />)} />
        <Route exact path="/simulator" ponent={RequireAuth(Simulator)} />
        <Route exact path="/dashboard" ponent={RequireAuth(Dashboard)} />
        <Route ponent={NotFoundPage} />
      </Switch>
      <FooterTemplate />
      <ScrollUpButton />
    </div>
  </BrowserRouter>
);

const mapStateToProps = (state, ownProps) => {
  return ({
    state: state,
    cookies: ownProps.cookies
  });
}

export const Routes = connect(mapStateToProps, null)(BrowserRoutes)

export default Routes

I believe the problem essentially arises here. By doing so, I thought I would have been able to use the cookies from every single ponent like this:

//get this.props.cookies
const { cookies } = this.props;

//setting a cookie
cookies.set('name', 'Ross', { path: '/' });

//getting a cookie
cookies.get('name');

However, that doesn't seem the case and I cannot get cookies to work in any of my ponents especially in my actions/auth.js. Does anyone have any suggestions? How can I efficiently use cookies in this scenario? I am assuming I can send down the cookies prop to each ponent that needs it but I am curious to find out what could be the best/cleanest way of using react-cookie with redux. I am fairly new to the MERN JavaScript software stack and mostly self-thought so I am a bit confused about some concepts. For example, if in Routes I am saving cookies into the redux's store, how can I access those cookies afterwards?

My main application is based on this old boilerplate which I have been slowly updating. Currently, all of the dependencies have been updated except for react-cookie.

I am trying to upgrade react-cookie to version 3.0.4 using this tutorial but I need some help overing some challenges I am facing during the transition process.

Following the tutorial, I changed index.js to

ReactDOM.render(
  <CookiesProvider>
    <Provider store={store}>
      <App />
    </Provider>
  </CookiesProvider>,
  document.querySelector('.wrapper'));

Now, my app.js file looks like this:

import React, { Component } from 'react'
import { withCookies } from 'react-cookie'
import Routes from '../Routes'

class App extends Component {
  render() {
    return (
      <div className="container">
        <Routes cookies={this.props.cookies} />
      </div>
    );
  }
}

export default withCookies(App)

Now, my biggest concern es here. My Routes ponent was never meant to be a Redux container so I changed it to this to acmodate the tutorial:

import React from 'react'
import { connect } from 'react-redux'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import ScrollUpButton from 'react-scroll-up-button'

// Import miscellaneous routes and other requirements
import NotFoundPage from './ponents/pages/not-found-page'

// Import Header and footer
import HeaderTemplate from './ponents/template/header'
import FooterTemplate from './ponents/template/footer'

// Import static pages
import HomePage from './ponents/pages/home-page'

// Import authentication related pages
import Register from './ponents/auth/register'
import Login from './ponents/auth/login'
import Logout from './ponents/auth/logout'
import ForgotPassword from './ponents/auth/forgot_password'
import ResetPassword from './ponents/auth/reset_password'
import ConfirmationMessage from './ponents/auth/confirmation_message'
import ResendVerificationEmail from './ponents/auth/resend_verification_email'

// Import dashboard pages
import Dashboard from './ponents/dashboard/dashboard'
import ChangePassword from './ponents/dashboard/profile/change-password'

// Import simulator pages
import Simulator from './ponents/simulator/index'

// Import higher order ponents
import RequireAuth from './ponents/auth/require_auth'

const BrowserRoutes = () => (
  <BrowserRouter>
    <div>
      <HeaderTemplate logo="Stress Path Simulator" />
      <Switch>
        <Route exact path="/" ponent={HomePage} />
        <Route exact path="/register" ponent={Register} />
        <Route exact path="/login" ponent={Login} />
        <Route exact path="/logout" ponent={Logout} />
        <Route exact path="/forgot-password" ponent={ForgotPassword} />
        <Route exact path="/reset-password/:resetToken" ponent={ResetPassword} />
        <Route exact path="/confirmation-message"  render={() => <ConfirmationMessage message="Please click on the link we sent to your email to verify your account." /> } />
        <Route exact path="/resend-verification-email" ponent={ResendVerificationEmail} />
        <Route exact path="/profile/change-password" ponent={RequireAuth(ChangePassword)} />
        <Route exact path="/confirmation-password-changed" render={() => RequireAuth(<ConfirmationMessage message="Password has been successfully changed!" />)} />
        <Route exact path="/simulator" ponent={RequireAuth(Simulator)} />
        <Route exact path="/dashboard" ponent={RequireAuth(Dashboard)} />
        <Route ponent={NotFoundPage} />
      </Switch>
      <FooterTemplate />
      <ScrollUpButton />
    </div>
  </BrowserRouter>
);

const mapStateToProps = (state, ownProps) => {
  return ({
    state: state,
    cookies: ownProps.cookies
  });
}

export const Routes = connect(mapStateToProps, null)(BrowserRoutes)

export default Routes

I believe the problem essentially arises here. By doing so, I thought I would have been able to use the cookies from every single ponent like this:

//get this.props.cookies
const { cookies } = this.props;

//setting a cookie
cookies.set('name', 'Ross', { path: '/' });

//getting a cookie
cookies.get('name');

However, that doesn't seem the case and I cannot get cookies to work in any of my ponents especially in my actions/auth.js. Does anyone have any suggestions? How can I efficiently use cookies in this scenario? I am assuming I can send down the cookies prop to each ponent that needs it but I am curious to find out what could be the best/cleanest way of using react-cookie with redux. I am fairly new to the MERN JavaScript software stack and mostly self-thought so I am a bit confused about some concepts. For example, if in Routes I am saving cookies into the redux's store, how can I access those cookies afterwards?

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Sep 10, 2018 at 17:33 Alessandro CaliAlessandro Cali 4191 gold badge6 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

Instead of passing the cookies from the App/Router down, it is better to wrap only the ponents that will need the cookies. For example your Login ponent would look like this:

class Login extends React.Component {
   render() {
      let { cookies } = this.props;
      let useCookie = cookies.get("testCookie");
      ...
   }
}

export default withCookies(connect(mapStateToProps, null)(Login));
Post a comment

comment list (0)

  1. No comments so far