Adding Routes to a React/Firebase app - reactjs

Just starting to add React Routes to a React/firebase app. I had this code to read the data,
const fb = firebase
.initializeApp(config)
.database()
.ref();
fb.on('value', snapshot => {
const store = snapshot.val();
ReactDOM.render(
<App {...store} />
,
document.getElementById('root')
);
});
This worked correctly, with real time updates to the App.
I then started to play with Router,
ReactDOM.render(
<Router>
<Route path="/" component={App {...store}} />
</Router>
,
document.getElementById('root')
);
But the {...store} gives an error, unexpected token. Should I move the Firebase code lower down the tree into the App component or is there a different way?

uh the component=doesn't take that thing that you have there with ReactDOM.render()
As you have it right now: store will be undefined... so set:
let store = {} // at the top
Where is your actual component/class defined?
also you shouldn't creator render based on when Firebase shows up you should render first then when firebase shows up you can update the state.
So there is a lot that will need to be fixed here before this can work.
Here is my index.js:
also notice that store is the result of the configureStore (I'm assuming you want to use Redux as you have a store)...
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import Root from './root/containers/Root'
import './index.css'
import configureStore from './root/store'
import { syncHistoryWithStore } from 'react-router-redux'
import { browserHistory } from 'react-router'
const store = configureStore()
const history = syncHistoryWithStore(browserHistory, store)
render(
<Root store={store} history={history} />,
document.getElementById('root')
);
My store:
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import reducer from '../reducers'
import { database, initializeApp } from 'firebase'
import { firebaseConfig } from '../constants'
initializeApp(firebaseConfig)
export const rootRef = database().ref().child('/react')
export const dateRef = rootRef.child('/date')
export default function configureStore(preloadedState){
const store = createStore(
reducer,
preloadedState,
applyMiddleware(thunkMiddleware, createLogger())
)
return store
}
And my Root:
import React, { Component, PropTypes } from 'react'
import { Provider } from 'react-redux'
import routes from './routes'
import { Router, } from 'react-router'
class Root extends Component {
render() {
const { store, history } = this.props
return (
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>
)
}
}
Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
Simplest Version to get started:
import React, { Component } from 'react'
import { firebaseConfig } from '../constants' //this is a must otherwise you have multiple versions of firebase running around...
initializeApp(firebaseConfig)
export const rootRef = database().ref().child('/root')
class App extends Component {
componentDidMount(){
initializeApp(firebaseConfig)
this.state = {store: {}}
rootRef.on('value', snapshot => {
this.setState({store: snapshot.val()});
}
}
render(){
let { store } = this.state
let childrenWithProps = React.Children
.map(this.props.children, function(child) {
return React.cloneElement(child, { store: store });
});
return <div>
{JSON.stringify(store)}
{childrenWithProps}
</div>
}
}
const Routes = (<Route component={App}><Route component={Comp1} path='/earg'/><Route component={Comp2} path='/earg'/></Route>)
render(Routes, document.getElementById('root'))
This is a lot of code and you'll need still more to get this going... I'd recommend a tutorial perhaps...

In the end, for a quick solution, I used an anonymous function to wrap the component,
<Route path="/" component={() => (<App {...store} />)} />

Related

How to fix "Could not find "store" in either the context or props of "Connect(Provider)" issue (ReactJs, Redux, SimpleWebRTC)?

I am trying to launch the SimpleWebRTC app from here: https://docs.simplewebrtc.com/#/?id=getting-started
App.js file:
import React from "react";
import { Provider } from "react-redux";
import ReduxToastr from "react-redux-toastr";
import store from "./redux/store/index";
import Routes from "./routes/Routes";
const App = () => (
<Provider store={store}>
<Routes />
<ReduxToastr
timeOut={5000}
newestOnTop={true}
position="top-right"
transitionIn="fadeIn"
transitionOut="fadeOut"
progressBar
closeOnToastrClick
/>
</Provider>
);
export default App;
./redux/store/index.js file:
import { combineReducers } from "redux";
import sidebar from "./sidebarReducers";
import layout from "./layoutReducer";
import theme from "./themeReducer";
import app from "./appReducer";
import auth from "./authReducer";
import { reducer as simplewebrtc } from '#andyet/simplewebrtc';
import { reducer as toastr } from "react-redux-toastr";
export default combineReducers({
sidebar,
layout,
theme,
toastr,
app,
auth,
simplewebrtc
});
./redux/store/index.js file:
import { createStore, applyMiddleware } from "redux";
import thunk from 'redux-thunk';
import rootReducer from "../reducers/index";
const persistedState = localStorage.getItem('reduxState') ? JSON.parse(localStorage.getItem('reduxState')) : {}
var store
if(persistedState.app){
store = createStore(rootReducer, persistedState, applyMiddleware(thunk));
}else{
store = createStore(rootReducer, applyMiddleware(thunk));
}
store.subscribe(()=>{
localStorage.setItem('reduxState', JSON.stringify(store.getState()))
})
export default store;
Chat.js file:
const API_KEY = '';
const ROOM_PASSWORD = 'test';
const CONFIG_URL = `https://api.simplewebrtc.com/config/guest/${API_KEY}`
const ROOM_NAME = 'uniq-room-name'
class _SimpleWebRtc extends React.Component {
constructor(props) {
super(props);
}
render(){
return (
<SWRTC.Provider configUrl={CONFIG_URL}> {/* <------- problem here */}
{/* Render based on the connection state */}
<SWRTC.Connecting>
<h1>Connecting...</h1>
</SWRTC.Connecting>
<SWRTC.Connected>
<h1>Connected!</h1>
<SWRTC.RequestUserMedia audio auto />
<SWRTC.Room name={ROOM_NAME} password={ROOM_PASSWORD}>
<SWRTC.RemoteAudioPlayer />
</SWRTC.Room>
</SWRTC.Connected>
</SWRTC.Provider>
)
}
}
const SimpleWebRtc = connect(store => ({simplewebrtc: store.simplewebrtc})) (_SimpleWebRtc)
When I trying run this code it returns a folloowing error for me:
app.js:58464 Uncaught Invariant Violation: Could not find "store" in either the context or props of "Connect(Provider)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(Provider)".
Do you have any ideas about what is wrong with this code and how to solve this issue?
I also faced this problem and solved the issue by updating the packages.
You have to use
react#^16.8.4
react-dom#^16.8.4
react-redux#^7.0.0
redux#^4.0.0
redux-thunk#^2.3.0
Here are the requirements for simplewebRTC
https://docs.simplewebrtc.com/#/ReactVersions

React Router hash router do not re-render the view

I have a front-end app built on top of react/redux/react-router. Now, I try to set up hash router. However, it only works on URL, but it does not re-render the UI.
Only way to see the view change is to refresh the browser. Then, now I see the view for the url.
When I used browser router, it automatically re-rendered the views. It will be great help if you can tell me what I missed for this current situation.
EDIT: Added my code
// index.tsx
import * as React from 'react';
import { Provider } from 'react-redux';
import { Router, Route, Switch } from 'react-router-dom';
import { Home } from './containers/home';
import { SMS } from './containers/sms';
import { history, store } from './store';
export const App = () => (
<Provider store={store}>
<Router basename="/" history={history}>
<Switch>
<Route exact path="/call" component={Home} />
<Route exact path="/sms" component={SMS} />
</Switch>
</Router>
</Provider>
);
// store.ts
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { syncHistoryWithStore, routerReducer } from 'react-router-redux';
import { createBrowserHistory, createHashHistory } from 'history';
import thunk from 'redux-thunk';
import { storage } from '../services/local-storage';
import { callsReducer } from './calls/reducer';
import { Call } from '../interfaces/call.interface';
import { CallMap } from '../interfaces/call-map.interface';
const STORAGE_NAME = 'SIP_CALL_SIMULATOR';
const {
loadState,
saveState,
} = storage({
name: STORAGE_NAME,
localStorage,
});
interface RootState {
calls: CallMap;
}
const initialState: RootState = {
calls: {},
};
const persistedState = loadState(initialState);
const reducer = combineReducers({
calls: callsReducer,
routing: routerReducer,
});
const store = createStore(reducer, persistedState, applyMiddleware(thunk));
// const browserHistory = createBrowserHistory();
const hashHistory = createHashHistory();
// const history = syncHistoryWithStore(browserHistory, store);
const history = syncHistoryWithStore(hashHistory, store);
store.subscribe(() => {
console.log(`Updated the redux store.`);
const state = store.getState();
console.log(state);
saveState(state);
});
export { history, store };
Thanks!

Server-side rendering using react-router 4, how to render client version?

I'm learning developing react.js server-side rendering web app, I'm using Express.js and Swig for the server-side
Code
server.js
import express from 'express'
import path from 'path'
import React from 'react'
import { StaticRouter } from 'react-router'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import setupSwig from 'setup.swig'
import { setupStore } from '../shared/redux/store'
import { ajaxFunction } from '../shared/services/Customer'
import App from '../shared/components/App'
const app = express()
app.use(express.static(path.resolve(__dirname, '..', '_public')))
setupSwig(app)
app.use((req, res) => {
const url = req.url
ajaxFunction()
.then(({ data: customers }) => {
const context = {}
const store = setupStore({
customers
})
const html = renderToString(
<Provider store={ store }>
<StaticRouter location={ url } context={ context }>
<App />
</StaticRouter>
</Provider>
)
const initState = store.getState()
res.render('./index.swig', { html, initState })
})
}
})
app.listen(3000)
client.js
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { BrowserRouter } from 'react-router-dom'
import { setupStore } from '../shared/redux/store'
import App from '../shared/components/App'
const initState = window.__INIT_STATE__
delete window.__INIT_STATE__
const store = setupStore(initState)
render(<Provider store={ store }>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>, document.getElementById('reactApp'))
Question
On the server.js I use <StaticRouter location={ url } context={ context }> but I have no ideas how to make ((what props to pass with) the <BrowserRouter> on client.js redirect to specific URL e.g. /customers, /about
If I did things wrong way please also guide
Thanks

react-router-redux, push method does not work

I am using react-router-redux.
I don't know how to create the demo to describe the issue simply.
I push all code on Github.
https://github.com/jiexishede/newReactSOAskDemo001
The a-href work well.
#https://github.com/jiexishede/newReactSOAskDemo001/blob/ask1/src/components/Home/Preview.js/#L37
Now, the push method does not work.
#https://github.com/jiexishede/newReactSOAskDemo001/blob/ask1/src/components/Home/Preview.js/#L30
I edit the code and update it on GitHub.
I import the hashHistory.
https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L9
hashHistory.push('detail/'+id); work well.
https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L32
disPatchpush #https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L31
It does not work.
In the Home.js:
#connect(state => {
return {
list:state.home.list,
};
}, dispatch => {
return {
actions: bindActionCreators(actions, dispatch),
dispatchPush: bindActionCreators(push, dispatch),
}
})
dispatchPush is passed from the Home.js to PreviewList to Preview.
Have your tried out?
handleClick(e) {
e.preventDefault();
this.props.history.push('/#/detail/' + id);
}
Tell me if it works or not and will update the answer accordingly.
Or if you want to try to navigate outside of components, try this.
Also try setting a route:
<Route path="/preview" component={Preview} />
That might get you the history prop.
you miss routerMiddleware. Works beautifully after applying routerMiddleware.
import { browserHistory } from 'react-router';
import { routerReducer, routerMiddleware } from 'react-router-redux';
...
const finalCreateStore = compose(
applyMiddleware(
ThunkMiddleware,
FetchMiddleware,
routerMiddleware(browserHistory)
),
DevTools.instrument(),
)(createStore);
const reducer = combineReducers({
...rootReducer,
routing: routerReducer,
});
export default function configureStore(initialState) {
const store = finalCreateStore(reducer, initialState);
return store;
}
Read this section of the docs - https://github.com/reactjs/react-router-redux#what-if-i-want-to-issue-navigation-events-via-redux-actions
If you want to navigate to another route, try Proptypes, like so:
import React, { Component, PropTypes } from 'react';
class Preview extends Component {
...
static contextTypes = {
router: PropTypes.object
};
handleNavigate(id,e) {
e.preventDefault();
this.context.router.push(`/#/detail/${id}`);
}
...
}
I had the same issue with react-router-redux and solved in the following way.
There is need to use Router not BrowserRouter. The history object has to be created with the createBrowserHistory method imported from history package.
Then the history has to be synchronized with the store using syncHistoryWithStore method imported from react-router-redux. This new history object will be passed to Router.
Then initialize the routerMiddleware passing to it the synchronized history object.
Please check out this code:
store.js
import createSagaMiddleware from 'redux-saga';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { routerReducer, routerMiddleware as reduxRouterMiddleware } from 'react-router-redux';
import { category, machine, machines, core } from './reducers';
import rootSaga from './sagas';
const rootReducer = combineReducers({
category,
machines,
machine,
core,
routing: routerReducer,
});
const initStore = (history = {}) => {
const sagaMiddleware = createSagaMiddleware();
const routerMiddleware = reduxRouterMiddleware(history);
const store = createStore(
rootReducer,
applyMiddleware(
sagaMiddleware,
routerMiddleware
)
);
sagaMiddleware.run(rootSaga);
return store;
}
export default initStore;
app.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Router } from 'react-router';
import { Provider } from 'react-redux';
import { createBrowserHistory } from 'history';
import { syncHistoryWithStore } from 'react-router-redux';
import './index.css';
import App from './App';
import initStore from './store';
import * as serviceWorker from './serviceWorker';
const browserHistory = createBrowserHistory();
const store = initStore(browserHistory)
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<App />
</Router>
</Provider>,
document.getElementById('root')
);
serviceWorker.unregister();
Connected React Router requires React 16.4 and React Redux 6.0 or later.
$ npm install --save connected-react-router
Or
$ yarn add connected-react-router
Usage
Step 1
In your root reducer file,
Create a function that takes history as an argument and returns a root reducer.
Add router reducer into root reducer by passing history to connectRouter.
Note: The key MUST be router.
// reducers.js
import { combineReducers } from 'redux'
import { connectRouter } from 'connected-react-router'
const createRootReducer = (history) => combineReducers({
router: connectRouter(history),
... // rest of your reducers
})
export default createRootReducer
Step 2
When creating a Redux store,
Create a history object.
Provide the created history to the root reducer creator.
Use routerMiddleware(history) if you want to dispatch history actions (e.g. to change URL with push('/path/to/somewhere')).
// configureStore.js
import { createBrowserHistory } from 'history'
import { applyMiddleware, compose, createStore } from 'redux'
import { routerMiddleware } from 'connected-react-router'
import createRootReducer from './reducers'
...
export const history = createBrowserHistory()
export default function configureStore(preloadedState) {
const store = createStore(
createRootReducer(history), // root reducer with router state
preloadedState,
compose(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
// ... other middlewares ...
),
),
)
return store
}
Step 3
Wrap your react-router v4/v5 routing with ConnectedRouter and pass the history object as a prop. Remember to delete any usage of BrowserRouter or NativeRouter as leaving this in will cause problems synchronising the state.
Place ConnectedRouter as a child of react-redux's Provider.
N.B. If doing server-side rendering, you should still use the StaticRouter from react-router on the server.
// index.js
import { Provider } from 'react-redux'
import { Route, Switch } from 'react-router' // react-router v4/v5
import { ConnectedRouter } from 'connected-react-router'
import configureStore, { history } from './configureStore'
...
const store = configureStore(/* provide initial state if any */)
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}> { /* place ConnectedRouter under Provider */ }
<> { /* your usual react-router v4/v5 routing */ }
<Switch>
<Route exact path="/" render={() => (<div>Match</div>)} />
<Route render={() => (<div>Miss</div>)} />
</Switch>
</>
</ConnectedRouter>
</Provider>,
document.getElementById('react-root')
)

React + Redux Server initialize with store and history

I've the following app:
Client
index.js
import React from "react";
import ReactDOM from "react-dom";
import Root from "./containers/Root";
import configureStore from "./store/configureStore";
import { browserHistory } from "react-router";
import { loginUserSuccess } from "./actions/auth";
import { syncHistoryWithStore } from "react-router-redux";
const target = document.getElementById("root");
const store = configureStore(browserHistory, window.__INITIAL_STATE__);
// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store)
const node = (
<Root store={store} history={history} />
);
let token = localStorage.getItem("token");
if (token !== null) {
store.dispatch(loginUserSuccess(token));
}
ReactDOM.render(node, target);
Root.js
import React from "react";
import {Provider} from "react-redux";
import AppRouter from "../routes/appRouter";
export default class Root extends React.Component {
static propTypes = {
store: React.PropTypes.object.isRequired,
history: React.PropTypes.object.isRequired
};
render () {
return (
<Provider store={this.props.store}>
<AppRouter history={this.props.history}>
</AppRouter>
</Provider>
);
}
}
AppRouter (routes/appRouter.js
import React from "react";
import routes from "./routes";
import { Router } from "react-router";
export default (
<Router routes={routes} history={this.props.history}></Router>
)
routes (routes/routes.js)
import React from "react";
import {Route, IndexRoute} from "react-router";
import { App } from "../containers";
import {HomeView, LoginView, ProtectedView, NotFoundView} from "../views";
import {requireAuthentication} from "../components/core/AuthenticatedComponent";
export default (
<Route path='/' component={App} name="app" >
<IndexRoute component={requireAuthentication(HomeView)}/>
<Route path="login" component={LoginView}/>
<Route path="protected" component={requireAuthentication(ProtectedView)}/>
<Route path="*" component={NotFoundView} />
</Route>
)
requireAuthentication (/component/core/AuthenticatedComponent.js)
import React from "react";
import {connect} from "react-redux";
import { push } from "react-router-redux";
export function requireAuthentication(Component) {
class AuthenticatedComponent extends React.Component {
componentWillMount () {
this.checkAuth(this.props.isAuthenticated);
}
componentWillReceiveProps (nextProps) {
this.checkAuth(nextProps.isAuthenticated);
}
checkAuth (isAuthenticated) {
if (!isAuthenticated) {
let redirectAfterLogin = this.props.location.pathname;
this.props
.dispatch(push(`/login?next=${redirectAfterLogin}`));
}
}
render () {
return (
<div>
{this.props.isAuthenticated === true
? <Component {...this.props}/>
: null
}
</div>
)
}
}
const mapStateToProps = (state) => ({
token: state.auth.token,
userName: state.auth.userName,
isAuthenticated: state.auth.isAuthenticated
});
return connect(mapStateToProps)(AuthenticatedComponent);
}
configureStore.js
import rootReducer from "../reducers";
import thunkMiddleware from "redux-thunk";
import {createStore, applyMiddleware, compose} from "redux";
import {routerMiddleware} from "react-router-redux";
import {persistState} from "redux-devtools";
import createLogger from "redux-logger";
import DevTools from "../dev/DevTools";
const loggerMiddleware = createLogger();
const enhancer = (history) =>
compose(
// Middleware you want to use in development:
applyMiddleware(thunkMiddleware, loggerMiddleware, routerMiddleware(history)),
// Required! Enable Redux DevTools with the monitors you chose
DevTools.instrument(),
persistState(getDebugSessionKey())
);
function getDebugSessionKey() {
if(typeof window == "object") {
// You can write custom logic here!
// By default we try to read the key from ?debug_session=<key> in the address bar
const matches = window.location.href.match(/[?&]debug_session=([^&#]+)\b/);
return (matches && matches.length > 0)? matches[1] : null;
}
return;
}
export default function configureStore(history, initialState) {
// Add the reducer to your store on the `routing` key
const store = createStore(rootReducer, initialState, enhancer(history))
if (module.hot) {
module
.hot
.accept("../reducers", () => {
const nextRootReducer = require("../reducers/index");
store.replaceReducer(nextRootReducer);
});
}
return store;
}
Server
server.js
import path from "path";
import { Server } from "http";
import Express from "express";
import React from "react";
import {Provider} from "react-redux";
import { renderToString } from "react-dom/server";
import { match, RouterContext } from "react-router";
import routes from "./src/routes/routes";
import NotFoundView from "./src/views/NotFoundView";
import configureStore from "./src/store/configureStore";
import { browserHistory } from "react-router";
// import { syncHistoryWithStore } from "react-router-redux";
// initialize the server and configure support for ejs templates
const app = new Express();
const server = new Server(app);
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "./"));
// define the folder that will be used for static assets
app.use("/build", Express.static(path.join(__dirname, "build")));
// // universal routing and rendering
app.get("*", (req, res) => {
const store = configureStore(browserHistory);
match(
{ routes, location: req.url },
(err, redirectLocation, renderProps) => {
// in case of error display the error message
if (err) {
return res.status(500).send(err.message);
}
// in case of redirect propagate the redirect to the browser
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
// generate the React markup for the current route
let markup;
if (renderProps) {
// if the current route matched we have renderProps
// markup = renderToString(<Provider store={preloadedState} {...renderProps}/>);
markup = renderToString(
<Provider store={store} >
<RouterContext {...renderProps} />
</Provider>
);
} else {
// otherwise we can render a 404 page
markup = renderToString(<NotFoundView />);
res.status(404);
}
// render the index template with the embedded React markup
const preloadedState = store.getState()
return res.render("index", { markup, preloadedState });
}
);
});
// start the server
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || "production";
server.listen(port, err => {
if (err) {
return console.error(err);
}
console.info(`Server running on http://localhost:${port} [${env}]`);
});
I don't know if I'm initializing correctly my store on the server-side.
How do I know this? Because renderProps is always null and thereby it returns NotFoundView.
However I made some modifications since I understood that my routes were being initialized incorrectly.
This made me use my configureStore(...) (which I use on client-side and it's working) on the server-side.
Now I'm getting the following error:
TypeError:Cannot read property 'push' of undefined
This error happens on AuthenticatedComponent in the following line:
this.props
.dispatch(push(`/login?next=${redirectAfterLogin}`));
It's strange since this works on client-side and on server-side it just throws this error.
Any idea?
PS
Am I doing it correctly by using the same Routes.js in client and server?
And the same for my configureStore(...)?
All the examples I see, they use a different approach to create the server-side store, with createStore from redux and not their store configuration from client-side.
PS2
I now understand that push may not work on server, only client (right?). Is there any workaround for this?
PS3
The problem I was facing was happening because I was rendering <Router /> into server, and my routes.js should only contain <Route /> nodes.
However, after a while I discovered that history shouldn't be configured in server and I just configured my store and passed it to the <Provider /> being rendered.
But now I need to compile my JSX and it throws:
Error: Module parse failed: D:\VS\Projects\Tests\OldDonkey\OldDonkey.UI\server.js Unexpected token (46:20)
You may need an appropriate loader to handle this file type.
| // markup = renderToString(<Provider store={preloadedState} {...renderProps}/>);
| markup = renderToString(
| <Provider store={store} >
| <RouterContext {...renderProps} />
| </Provider>

Resources