I have a React application with a button that features a toogle, this toggle allows to show or hide some views in the page, therefore if the user hits the toogle button it will see one view (Toggle ON View) or the other (Toggle OFF View). I have to store the value of this toggle in a cookie, to ensure that when the user visits again the site it will see the last view selected (Toggle ON or Toggle OFF).
I tried to solve this in the simpliest way by creating a new react app from the scratch using "npx create-react-app". I also have included the npm react-cookie library.
This works fine when the user hits toggle button, the proper value is being set in the cookie and the right view is being shown. However, if I reload the page it's always showing the incorrect view ignoring the value loaded from cookie. I can't explain why this is happening only when the page loads.
Index.js code:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { CookiesProvider } from 'react-cookie';
ReactDOM.render(<CookiesProvider>
<App />
</CookiesProvider>,
document.getElementById('root'));
serviceWorker.unregister();
App.js code:
import React, { Component } from 'react';
import { instanceOf } from 'prop-types';
import './App.css';
import { withCookies, Cookies } from 'react-cookie';
class App extends Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
};
constructor(props) {
super(props);
const { cookies } = props;
var valueToSet = cookies.get('toggleMode');
console.log('Toggle Value from Cookie: ' + valueToSet);
this.state = {
toogle: cookies.get('toggleMode')
};
}
toggleTableModeButtons = () => {
return (
<div>
<button type="button" onClick={this.toggleMode}>Toggle Now!</button>
</div>
);
};
toggleMode = event => {
const { cookies } = this.props;
event.preventDefault();
var toogleValueToSet = !this.state.toogle;
this.setState(
{ toogle: toogleValueToSet }
);
console.log('Setting Cookie with value: ' + toogleValueToSet);
cookies.set('toggleMode', toogleValueToSet, { path: '/' });
}
render() {
const { toogle } = this.state;
console.log('Toggle Value in RENDER: ' + toogle);
return (
<div>
{this.toggleTableModeButtons()}
<h1>
{
toogle ? "Toggle ON (View 1)" : "Toggle OFF (View 2)"
}
</h1>
</div>
);
}
}
export default withCookies(App);
I need to know what i'm doing wrong in this example. Any help would be really appreaciated.
Your cookies give you back string not boolean, You can try changing your console log as below which will print "string", When the state is getting updated with cookie value. Your condition toogle ? will always return true if there is something in toogle, which is the case when you set toogle from cookies.
console.log('Toggle Value in RENDER: ' + typeof toogle);
Parse your cookie value with JSON as below so it will work.
this.state = {
toogle: JSON.parse(cookies.get('toggleMode')) || false
};