Running local environment with in create react-app displays %20? - javascript

I recently had to format my computer, but was given the option to save my files which I did. My project files are all there and good as far as I could tell. But when I do npm start it spins of the project without any errors, but then the URL bar displays this address:
http://localhost:3000/pages%20/%20login%20-%20page
instead of:
http://localhost:3000/pages/login-page
Note: This did not happen before I had to format my computer.
Steps I tried:
Remove node modules, then run npm i
Remove the %20 and hit enter, returns same thing in the URL bar
index.js
import { createBrowserHistory } from "history";
import jwt_decode from "jwt-decode";
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Router, Route, Switch } from "react-router-dom";
import "./assets/scss/material-dashboard-pro-react.css";
import Pages from "./layouts/Pages.jsx";
import { setCurrentUser, logoutUser } from "./oldComp/actions/authActions";
import { clearCurrentProfile } from "./oldComp/actions/profileActions";
import store from "./oldComp/store";
import setAuthToken from "./oldComp/utils/setAuthToken";
import PrivateRoute from "./PrivateRoute";
import { indexRoutes } from "./routes/index.jsx";
import Profile from "./views/Community/ProfilePage/ProfilePage";
import { fetchAllLessons } from "./oldComp/actions/mentorLessonActions";
const hist = createBrowserHistory();
// Check for token
if (localStorage.jwtToken) {
// Set auth token header auth
setAuthToken(localStorage.jwtToken);
// Decode token and get user info and exp
const decoded = jwt_decode(localStorage.jwtToken);
// Set user and isAuthenticated
store.dispatch(setCurrentUser(decoded));
fetchAllLessons();
// Check for expired token
const currentTime = Date.now() / 1000;
if (decoded.exp < currentTime) {
// Logout user
store.dispatch(logoutUser());
// Clear current Profile
store.dispatch(clearCurrentProfile());
// Redirect to login
window.location.href = "/pages";
}
}
ReactDOM.render(
<Provider store={store}>
<Router history={hist}>
<div>
<Route path="/pages" name="Pages" component={Pages} />
<Switch>
{indexRoutes.map((prop, key) => {
return (
<PrivateRoute
path={prop.path}
component={prop.component}
key={key}
/>
);
})}
</Switch>
<Switch>
<PrivateRoute component={Profile} path="/partner-profile/:handle" />
</Switch>
</div>
</Router>
</Provider>,
document.getElementById("root")
);

I searched my files and had a redirect that had spaces in it.
This probably happened because I downloaded Beautify and it may have formatted some files that I wasn't aware of

Related

React renders component after Redux Selector pulls data

My app conditionally renders a login page or a Home Screen depending on whether a user is null or not. However, the app renders after Firebase has authenticated the user, so I can't seem to render the home screen page even though the user is logged in:
import React, { useEffect, useState} from 'react';
import './App.css';
import HomeScreen from './screens/HomeScreen';
import LoginScreen from './screens/LoginScreen';
import {auth} from "./firebase"
import {
BrowserRouter as Router,
Routes,
Route,
} from "react-router-dom"
import {useDispatch, useSelector} from "react-redux"
import {logout, login, selectUser} from "./features/userSlice"
function App() {
const user = useSelector(selectUser);
const dispatch = useDispatch();
useEffect(()=>{
const unsubscribe = auth.onAuthStateChanged(
(userAuth)=>{
if(userAuth){
dispatch(login({
uid: userAuth.uid,
email: userAuth.email
})
);
console.log(userAuth.email);
}
else{
dispatch(logout)
}
});
return unsubscribe;
}, []);
console.log(user);
return (
<div className="app">
<Router>
{!user? (
<LoginScreen></LoginScreen>
): (
<Routes>
<Route path="/" element={<HomeScreen />} />
<Route path="/test" element={<h1>hello world</h1>} />
</Routes>
)}
</Router>
</div>
);
}
export default App;
How am I able to render the app AFTER firebase authenticates the user, and stores user information into a slice? Only then will a selector to that data in the slice return as non null.

My react route is redirecting to localhost:3000 and not the page it should redirect to

I have 2 components both are exactly the same. one is redirected to when I click on a Navlink inside of my navbar that I created using react-bootstrap. The other component that is exactly the same just redirects to localhost:3000 and not "./member" when I click on the html button that should redirect to that component. Please help me.
the html button and the function to redirect look like
import {Link, Route, withRouter, useHistory} from 'react-router-dom'
const Posts = (props) => {
const dispatch = useDispatch();
const history = useHistory();
const getProfile = async (member) => {
// const addr = dispatch({ type: 'ADD_MEMBER', response: member })
console.log(member)
history.push('/member')
}
return (
<div>
<button onClick={() => getProfile(p.publisher)}>Profile</button>
</div>
)
}
export default withRouter(Posts);
The routes.js looks like
const Routes = (props) => {
return (
<Switch>
<Route path="/member" exact component={Member} />
</Switch>
)
}
export default Routes
The component that I am trying to redirect to is exactly the same as one that is redirected to and working when I click on it from the navlink. I have downgraded to history 4.10.1
My index.js is
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Router, Route } from 'react-router-dom';
import * as history from 'history';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import rootReducer from './reducers'
const store = createStore(rootReducer)
const userHistory = history.createBrowserHistory();
ReactDOM.render(
<Provider store = {store}>
<Router history={userHistory}>
<BrowserRouter>
<Route component={App} />
</BrowserRouter>
</Router>
</Provider>,
document.getElementById('root'));
serviceWorker.unregister();
When I wrap the app route in the url goes to ./member but it does not load.
<Switch>
<Route path="/" exact component={app} />
<Route path="/member" component={Member} />
</Switch>
<button onClick={() => history.push(`/${p.publisher}`)}>Profile</button>

React Router and customHistory push not rendering new component

I am using Router and customHistory to help me redirect the pages, but the pages not render correctly.
The code works like this: if the user is authorized or log in, then the user should be redirected to "localhost:8080/dashboard" and see the dashboard(with data fetching from firebase) & header; if the use is log out, then the user should be redirect to "locahost:8080/" and see the log in button with the header.
However, after I successfully log in, the url is "localhost:8080/dashboard" without any data fetched from firebase, only things I can see are the header and login button. But if I hit "RETURN" with the current url which is "localhost:8080/dashboard", it will redirect to correct page with all data fetching from firebase, and no login button.
This is the github_link to the code.
I have spent times searching online, but do not find any positive result except this one. After reading the stackoverflow I feel my code has some problems with asynchronization. Any thoughts?
I really appreciate for your help! Thanks!
This is my AppRouter.js:
export const customHistory = createBrowserHistory();
const AppRouter = () => (
<Router history={customHistory}>
<div>
<Header />
<Switch>
<Route path="/" exact component={LoginPage} />
<Route path="/dashboard" component={ExpenseDashboardPage} />
<Route path="/create" component={AddExpensePage} />
<Route path="/edit/:id" component={EditExpensePage} />
<Route path="/help" component={HelpPage} />
<Route component={LoginPage} />
</Switch>
</div>
</Router>
);
This is my app.js
import React, { Children } from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import "normalize.css/normalize.css"; //Normalize.css makes browsers render all elements more consistently and in line with modern standards.
import "./styles/styles.scss";
import AppRouter, { customHistory } from "./routers/AppRouter";
import configureStore from "./redux/store/configStore";
import { startSetExpenses } from "./redux/actions/expenses";
import { login, logout } from "./redux/actions/auth";
import "react-dates/lib/css/_datepicker.css";
import { firebase } from "./firebase/firebase";
//for testing: npm test -- --watch
const store = configureStore();
const jsx = (
<Provider store={store}>
<AppRouter />
</Provider>
);
ReactDOM.render(<p>Loading...</p>, document.getElementById("app"));
let hasRendered = false;
const renderApp = () => {
if (!hasRendered) {
ReactDOM.render(jsx, document.getElementById("app"));
hasRendered = true;
}
};
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log("log in");
store.dispatch(login(user.uid));
store.dispatch(startSetExpenses()).then(() => {
renderApp();
if (customHistory.location.pathname === "/") {
customHistory.push("/dashboard");
}
});
} else {
console.log("log out");
store.dispatch(logout());
renderApp();
customHistory.push("/");
}
});
This is the header.js
import React from "react";
import { BrowserRouter, Route, Switch, Link, NavLink } from "react-router-dom";
import { connect } from "react-redux";
import { startLogout } from "../redux/actions/auth";
export const Header = ({ startLogout }) => (
<header>
<h1>Expensify</h1>
<NavLink to="/" activeClassName="is-active">
Dashboard
</NavLink>
<NavLink to="/create" activeClassName="is-active">
CreateExpense
</NavLink>
<button onClick={startLogout}>Logout</button>
</header>
);
const mapDispatchToProps = (dispatch) => ({
startLogout: () => dispatch(startLogout()),
});
export default connect(undefined, mapDispatchToProps)(Header);

What does it meant - Browser history needs a DOM? [duplicate]

I am trying server side rendering using react-router 4. I am following the example provided here https://reacttraining.com/react-router/web/guides/server-rendering/putting-it-all-together
As per the example on server we should use StaticRouter. When I import as per the example I am seeing StaticRouter as undefined
import {StaticRouter} from 'react-router';
After doing some research online I found I could use react-router-dom. Now my import statement looks like this.
import {StaticRouter} from 'react-router-dom';
However when I run the code I am getting Invariant Violation: Browser history needs a DOM in the browser.
my server.js file code
....
app.get( '*', ( req, res ) => {
const html = fs.readFileSync(path.resolve(__dirname, '../index.html')).toString();
const context = {};
const markup = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context} >
<App/>
</StaticRouter>
);
if (context.url) {
res.writeHead(302, {
Location: context.url
})
res.end();
} else {
res.send(html.replace('$react', markup));
}
} );
....
And my client/index.js code
....
ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>
), root);
....
Update v1
Reduced my example to a bear minimum and still getting the same error.
clientIndex.js
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import App from '../App'
ReactDOM.render((
<BrowserRouter>
<App/>
</BrowserRouter>
), document.getElementById('app'))
serverIndex.js
import { createServer } from 'http'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { StaticRouter } from 'react-router'
import App from '../App'
createServer((req, res) => {
const context = {}
const html = ReactDOMServer.renderToString(
<StaticRouter
location={req.url}
context={context}
>
<App/>
</StaticRouter>
)
res.write(`
<!doctype html>
<div id="app">${html}</div>
`)
res.end()
}).listen(3000);
App.js
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import routes from "./client/routes";
const App = ( ) => (
<Router>
<Route path="/" exact render={( props ) => ( <div>Helloworld</div> )} />
</Router>
)
export default App;
You need to use different history provider for server side rendering because you don't have a real DOM (and browser's history) on server. So replacing BrowserRouter with Router and an alternate history provider in your app.js can resolve the issue. Also you don't have to use two wrappers. You are using BrowserRouter twice, in app.js as well as clientIndex.js which is unnecessary.
import { Route, Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
const history = createMemoryHistory();
<Router history={history}>
<Route path="/" exact render={( props ) => ( <div>Helloworld</div> )} />
</Router>
You can now replace StaticRouter with ConnectedRouter which can be used both in client and server. I use the following code to choose between history and export it to be used in ConnectedRouter's history.
export default (url = '/') => {
// Create a history depending on the environment
const history = isServer
? createMemoryHistory({
initialEntries: [url]
})
: createBrowserHistory();
}
In clientIndex.js
Rather than BrowserRouter use StaticRouter.
import { BrowserRouter } from 'react-router-dom';
import { StaticRouter } from 'react-router-dom'
As is essentially noted in the comments, one may hit this error (as I have) by accidentally wrapping your App component in a <BrowserRouter>, when instead it is your client app that should be wrapped.
App.js
import React from 'react'
const App = () => <h1>Hello, World.</h1>
export default App
ClientApp.js
import React from 'react'
import { BrowserRouter } from 'react-router-dom'
import ReactDOM from 'react-dom'
import App from './App'
const render = Component => {
ReactDOM.render(
<BrowserRouter>
<Component />
</BrowserRouter>,
document.getElementById('app')
)
}
render(App)
See also the React Router docs.

Page is continuously getting refreshed automatically

I have a react app where on loading the App component first the app checks whether there is token in localstorage, If it is there then it takes the token and verifies it, If the token is valid then the user is taken to dashboard and if it isn't the user is taken to login page, But however what is happening is that the page is getting continuosly refreshed, I have used window.location.href to redirect the user to other page, Am I doing something wrong please let me know I have posted the code below
import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import setAuthToken from "./utils/setAuthToken";
import jwtDecode from "jwt-decode";
import store from "./store/store";
import Dashboard from "./components/app/Dashboard";
import HomePage from "./components/homepage/HomePage";
import Navbar from "./components/common/Navbar";
import { UserDetails } from "./components/common/UserDetails";
import { Provider } from "react-redux";
import { logoutUser } from "./store/actions/authActions";
import { setCurrentUser } from "./store/actions/usersActions";
class App extends Component {
componentDidMount() {
if (localStorage.getItem("user")) {
const token = localStorage.getItem("user");
console.log("token available");
const decoded = jwtDecode(token);
var currentTime = Date.now().toString();
currentTime = currentTime.substring(0, currentTime.length - 3);
const currentTimeNum = parseInt(currentTime);
if (currentTimeNum > decoded.exp) {
console.log("logged out");
setAuthToken();
store.dispatch(logoutUser());
window.location.href = "/home-page";
} else {
console.log("logged in");
setAuthToken(token);
window.location.href = "/";
store.dispatch(setCurrentUser());
}
} else {
console.log("logged out");
setAuthToken();
window.location.href = "/home-page";
}
}
render() {
return (
<Provider store={store}>
<BrowserRouter>
<div className="App">
<Navbar />
<Switch>
<Route path="/home-page" component={HomePage} exact />
<Route path="/" component={Dashboard} exact />
<Route path="/user/:username" component={UserDetails} exact />
</Switch>
</div>
</BrowserRouter>
</Provider>
);
}
}
export default App;
remove the BrowserRouter from App.js and put it above app by doing this in index.js ->
<BrowserRouter> <App> <BrowserRouter/>
and replace this
window.location.href = "/foo-bar"
with this
this.props.history.push("/foo-bar")
or
this.props.history.replace("/foo-bar")
In your code, if the token is valid, you redirect the user to “/“ performing a browser refresh. This will trigger the entire webapp to reload and so App component componentDidMount to be called, the token will be valid again and the page will refresh again to "/".
Instead of using location.href you should use the history object:
import { createBrowserHistory } from 'history';
import { Router } from 'react-router';
const history = createBrowserHistory();
class App extends Component {
componentDidMount() {
// instead of window.location.href = 'some-url'
history.push('/some-url');
}
//..
render() {
return (
<Provider store={store}>
<Router history={history}>
{/* ... */}
</Router>
</Provider>
)
}
}

Categories

Resources