I having an issue with the Redux store in getting react_on_rails
where I want to switch the page and it doesn't work correctly for me. I am losing the redux store if I change the page or reload it.
Also, I am sorry for a pile of code I put, but I really don't know anything else or ways to fix it, the official docs for react_on_rails
and redux did not help me and it more likely confuse me how it should work. if anyone has a clue how to make it work, in advance, thank you
rootStore.js
import { combineReducers, applyMiddleware, createStore } from 'redux';
import middleware from 'redux-thunk';
import reducers from '../reducers';
export default (props, railsContext) => {
// eslint-disable-next-line no-param-reassign
delete props.prerender;
const combinedReducer = combineReducers(reducers);
const newProps = { ...props, railsContext };
return applyMiddleware(middleware)(createStore)(combinedReducer, newProps);
};
reducers/index.js
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import cartReducer from './cartReducer';
const rootReducer = combineReducers({
routing: routerReducer,
cart: cartReducer,
});
export default rootReducer;
the component that I am trying to do magic with
// @flow
import * as React from 'react';
import { connect } from 'react-redux';
import { addToCart} from '../actions/setCart';
import styles from './AddToCart.module.scss';
type Props = {
productId: number,
}
type State = {}
class AddToCart extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
}
onClick = () => {
console.log(this.props.productId);
this.props.addToCart(this.props.productId);
};
render() {
console.log('this.props.cart', this.props.cart);
return <button
onClick={this.onClick}
className={styles.button}
>Add To Cart</button>;
}
}
const AddToCartRedux = connect(
state => ({
cart: state.cart,
}),
dispatch => ({
addToCart: id => {
dispatch(addToCart(id));
},
}),
)(AddToCart);
export default AddToCartRedux;
my entry point
import ReactOnRails from 'react-on-rails';
import ProductDetailPage from '../pages/ProductDetailPage';
import rootStore from '../store/rootStore';
ReactOnRails.setOptions({
traceTurbolinks: true,
});
ReactOnRails.register({ProductDetailPage});
ReactOnRails.registerStore({rootStore});
my layout application
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= notice %>
<%= alert %>
<%= redux_store('rootStore', props: {}) %>
<%= react_component('ProductDetailPage', props: {product: @product.id}) %>
<%= yield %>
<%= redux_store_hydration_data %>
</body>
</html>