css style removes upon page refresh in vue project - css

When I first go to this link the header footer style is alright-
But then when I refresh or reload the page, the style is gone. How to fixed this?
Below is My router.js-
import { createWebHistory, createRouter } from "vue-router";
import Home from '../components/Home.vue';
import Organization from '../components/aboutus/Organization.vue';
const router = createRouter({
history: createWebHistory(),
base: process.env.BASE_URL,
scrollBehavior() {
return { x: 0, y: 0 }
},
routes: [
{
name:'Home',
path:'/',
component:Home
},
{
name:'Organization',
path:'/about_us/organization',
component:Organization
},
],
})
router.beforeEach((to, _, next) => {
return next()
})
// ? For splash screen
// Remove afterEach hook if you are not using splash screen
router.afterEach(() => {
// Remove initial loading
/*const appLoading = document.getElementById('loading-bg')
if (appLoading) {
appLoading.style.display = 'none'
}*/
})
export default router
Below is the main.js-
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/router'
import store from './store/index'
createApp(App).use(
router,
store,).mount('#app')

Related

How to Scroll to the top on page change in React Location?

How to make ScrollToTop component like in React Router? I would like to move page view to the top on page change.
Here's an example:
index.js
import React from "react";
import ReactDOM from "react-dom/client";
import {
createBrowserRouter,
RouterProvider,
} from "react-router-dom";
import ScrollToTop from "./ScrollToTop"
import "./index.css";
const router = createBrowserRouter([
{
path: "/",
element: <div>Hello world!</div>,
},
]);
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<ScrollToTop/>
<RouterProvider router={router} />
</React.StrictMode>
);
ScrollToTop.js
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
// "document.documentElement.scrollTo" is the magic for React Router Dom v6
document.documentElement.scrollTo({
top: 0,
left: 0,
behavior: "instant", // Optional if you want to skip the scrolling animation
});
}, [pathname]);
return null;
}
How to create the same with the use of React Location (Tanstack Router)?
We can achieve the same behaviour by using useLocation() hook in the TanStack library, but the props will be different - instead of pathname it is called current.
Here's the code for ScrollToTop.js:
import {useEffect } from "react";
import {useLocation} from "#tanstack/react-location";
export default function ScrollToTop() {
const {current} = useLocation();
useEffect(() => {
document.documentElement.scrollTo({
top: 0,
left: 0,
behavior: "instant", // Optional if you want to skip the scrolling animation
});
}, [current]);
return null;
}

Access current route inside a getter in Pinia?

I would like to know what is the current route so that I can compute the size of the sidebar.
import { defineStore } from 'pinia'
export const useSidebarStore = defineStore('sidebar', {
state: () => {
return {
full: true // can be toggled by clicking on the sidebar toggle button
}
},
getters: {
// TODO secondarySidebar is open if current route is settings
// secondarySidebarOpen: (state) =>
// TODO create a getter that returns the current route
currentRoute (state, getters, rootState, rootGetters) {
return
}
},
actions: {
}
})
export default useSidebarStore
Can you please help?
A solution I found is to store the current route to the state of the store by using beforeEach method of the router.
import { createRouter, createWebHistory } from 'vue-router'
import routes from '#/router/routes.js'
import { useSidebarStore } from '#/stores/sidebar.js'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes
})
router.beforeEach(async (to) => {
const sidebarStore = useSidebarStore()
sidebarStore.currentRoutePath = to.path
return true
})
export default router

Not able to fetch url params in vue js

Hi I am trying to fetch the value for "customerID" and "iot" in MyIOT.vue. When I enter the url http://localhost:8080/5/345435 it gives me an empty value for params. I tried both ways using routing and props. None of them is working. Not sure where I am getting it wro
main.js
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import MyIot from './components/MyIOT.vue'
//import router from './router/index.js'
const routes = [
// {
// path: '/',
// redirect: '/:customerID/:iot'
// },
{
path: '/:customerID/:iot',
component: MyIot,
//props: true,
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
const app = createApp(App).use(router);
app.mount('#app');
App.vue
<template>
<MyIot />
</template>
<script>
import MyIot from './components/MyIOT.vue'
//import axios from "axios";
export default {
name: "App",
components: {
MyIot,
},
};
</script>
components/MyIOT.vue
<template>
<div>customer id is: {{customerID}} and iot is : {{iot}}
</div>
</template>
<script>
import { useRoute } from 'vue-router'
export default {
name: 'MyIot',
//props: ['customerID', 'iot'],
setup() {
const route = useRoute();
console.log(route.params);
}
}
</script>

How to Debug White Screen Page (No Content Showing) in RN Expo App with No Error Prompts

I've been building an app in React Native Expo. First, I incorporated Facebook Login simply by copying and pasting the login async code into Login.js and added this.login() to componentWillMount. This worked - With the Facebook login popup showing up as app loads. I was able to log into my FB account with a success message.
However, as soon as I tried to incorporate Firebase, particularly somewhere between transferring code between my Home.js page and the Login.js page, I started getting this white screen to appear on page load.
There are no errors in a terminal; except a message that FacebookAppID and facebookDisplayName do not belong in app.json.
I tried adding a different background color (black) in CSS, which works, but still, there is no content.
Removing FacebookAppID and facebookDisplayName from app.json, which did nothing.
Updating my App Key to the correct one (I was missing the last number).
Restarted the terminal, expo web terminal x code and metro builder several times.
Updated my code so that every file in my Screens directory has { connect } & { login } imports as well as functionMapStateToProps and export default connect statements at bottom.
I tried changing a tab in TabNavigator.js to Login page, and using "Login" as the initialRouteName, but got an error that Login.js isn't a React component.
The first page that should show up before any other is the Facebook login...So it would seem the issue is there.
App.js
import React from 'react';
import Login from './screens/Login';
import reducers from './redux/reducers';
import thunkMiddleware from 'redux-thunk';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
const middleware = applyMiddleware(thunkMiddleware);
const store = createStore(reducers, middleware);
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<Login/>
</Provider>
);
}
}
------ end of App.js ------------
Login.js
import React from 'react';
import styles from '../styles'
import RootNavigator from '../navigation/RootNavigator';
import { connect } from 'react-redux';
import { login } from '../redux/actions';
import * as firebase from 'firebase';
import firebaseConfig from '../config/firebase.js';
firebase.initializeApp(firebaseConfig)
import {
Text,
View,
TouchableOpacity
} from 'react-native';
class Login extends React.Component
state = {}
componentWillMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user != null) {
this.props.dispatch(login(true))
console.log("We are authenticated now!" + JSON.stringify(user));
}
});
}
login = async () => {
const { type, token } = await Expo.Facebook.logInWithReadPermissionsAsync('YourAppKeyGoesHere', {
permissions: ['public_profile'],
});
if (type === 'success') {
// Build Firebase credential with the Facebook access token.
const credential = await firebase.auth.FacebookAuthProvider.credential(token);
// Sign in with credential from the Facebook user.
firebase.auth().signInWithCredential(credential).catch((error) => {
// Handle Errors here.
Alert.alert("Try Again")
});
}
}
render() {
if(this.props.loggedIn){
return (
<RootNavigator/>
)
} else {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.login.bind(this)}>
<Text>{this.props.loggedIn}</Text>
</TouchableOpacity>
</View>
)
}
}
}
function mapStateToProps(state) {
return {
loggedIn: state.loggedIn
};
}
export default connect(mapStateToProps)(Login);
---------end of Login.js ----------
Home.js
import React from 'react';
import styles from '../styles';
import { connect } from 'react-redux';
import { login } from '../redux/actions';
import {
Text,
View,
Alert
} from 'react-native';
class Home extends React.Component {
state = {}
componentWillMount() {
}
render() {
return (
<View>
<Text>Home</Text>
</View>
)
}
}
function mapStateToProps(state) {
return {
loggedIn: state.loggedIn
};
}
export default connect(mapStateToProps)(Home);
-----end of Home.js ------
redux folder
actions.js
export function login(){
return function(dispatch){
dispatch({ type: 'LOGIN', payload: input });
}
}
----end of actions.js ----
reducers.js
export default reducers = (state = {
loggedIn: false,
}, action) => {
switch (action.type) {
case 'LOGIN': {
return { ...state, loggedIn: action.payload }
}
}
return state;
}
------end of reducers.js ------
-----end of redux folder ------
-----navigation folder (react navigation) -------
---RootNavigator.js---
import React from 'react';
import TabNavigator from './TabNavigator';
import {
createDrawerNavigator,
createStackNavigator,
createBottomTabNavigator,
createAppContainer,
} from 'react-navigation';
const AppNavigator = createStackNavigator(
{
Main: {
screen: TabNavigator,
},
}
);
const AppContainer = createAppContainer(AppNavigator);
export default class RootNavigator extends React.Component {
render() {
return <AppContainer/>;
}
}
----end of RootNavigator.js-----
----TabNavigator.js----
import React from 'react';
import Home from '../screens/Home';
import Profile from '../screens/Profile';
import Matches from '../screens/Matches';
import {
createDrawerNavigator,
createStackNavigator,
createBottomTabNavigator,
createAppContainer,
createMaterialTopTabNavigator,
} from 'react-navigation';
export default createBottomTabNavigator(
{
Profile: {
screen: Profile,
navigationOptions: {
tabBarLabel: 'Profile',
},
},
Home: {
screen: Home,
navigationOptions: {
tabBarLabel: 'Home',
}
},
Matches: {
screen: Matches,
navigationOptions: {
tabBarLabel: 'Matches',
},
},
},
{
navigationOptions: {
header: null
},
tabBarPosition: 'top',
initialRouteName: 'Home',
animationEnabled: true,
swipeEnabled: true,
tabBarOptions: {
style: {
height: 75,
backgroundColor: 'blue'
},
}
}
);
-----end of TabNavigator----
Have you tried remote js Debugging?
What you can do is, Debugg JS remotely.
https://developers.google.com/web/tools/chrome-devtools/remote-debugging/
try to console.log("hi"); when your first component of your app mounts.
Try to add it in login page when the login component mounts.
That will help you debug unseen error which gets listed in the js debugger.
Just check those errors and follow up!
You're good to go!
I was also getting splash logo white screen, tired possible solution nothing works out, at last I have remove node_module and yarn.lock. then reinstall and update expo
follows cmd:-
$ npm install
$ yarn add expo
$ expo update
try this , works for me.
!!enjoy!!
As the other answer suggests, once you've done console.log to see the component is actually loading, then for me the issue was I couldn't actually see the content.
My solution was to wrap my content with a <View> to align the content in the middle of the page.
I understand your question is more complex than that, but hopefully, my answer might be able to help other people.
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'space-around',
}}>
<Text>Can you see this?</Text>
</View>
in my case,
style = {{ borderColor : #fff }}
my mistake is exceptin ' at borderColor value...
fix change to
style = {{ borderColor : '#fff' }}
Some components such as useState was imported from wrong url, I changed it and imported it from react and fixed it

Navigating between same components using Back/Forward browser buttons does not work

Hi I'm having trouble navigating with a browsers back/forward buttons. It only occurs when navigating between routes that share the same component via route parameters.
I have an application that lists lots of animals. Every time I navigate to example.com/animal/cat or example.com/animal/dog, a Http Get request is made to a restful Api which returns the relevant data. If I navigate to /animal/cat then to /animal/dog everything seems ok. The problem starts when I click on the browsers Back Button to go back to /animal/cat. Instead of loading the data for the cat, the URL changes but the data is still listed for the dog. I'm using router 3.0.0-beta.2 with RC4.
heres my animals details.component page:
import { Component, OnInit, OnDestroy } from '#angular/core';
import { ROUTER_DIRECTIVES, ActivatedRoute, Router } from '#angular/router';
import { Response } from '#angular/http';
import { Subscription } from 'rxjs/Rx';
import { DataService } from '../../data.service';
#Component({
moduleId: module.id,
selector: 'animal-details',
templateUrl: 'animal-details.component.html',
styleUrls: ['animal-details.component.css'],
directives:[ROUTER_DIRECTIVES]
})
export class AnimalDetailsComponent implements OnInit, OnDestroy {
constructor(private activatedRoute: ActivatedRoute, private dataService: DataService, private router: Router) {
}
private subscription: Subscription;
animal = {};
link: string;
table = 'animal/';
private url = '?related=family_by_link';
ngOnInit() {
this.subscription = this.activatedRoute.params.subscribe(
(param: any) => this.link = param['link']
);
this.dataService.getData(this.table, this.link, this.url)
.map((response: Response) => response.json())
.subscribe(
(data: any) => {this.animal = data},
err => { console.log('error404') }
);
};
nextData(){
this.dataService.getData(this.table, this.link, this.url)
.map((response: Response) => response.json())
.subscribe(
(data: any) => {this.animal = data},
err => { console.log('error404') }
);
window.scroll(0,0);
};
ngOnDestroy() {
this.subscription.unsubscribe();
};
}
I use the getData() method when navigating between animals on the same component. My AnimalComponentDetails html:
<div class="row">
<div class="col-sm-6 col-md-4 col-lg-3 text-xs-center" *ngFor="let family of animal.family_by_link" (click)="nextData()">
<a [routerLink]="['/animal', family.ani_link]">
<img src="/images/animal/{{family.ani_link}}.png">
<p>{{family.name}}</p>
</a>
</div>
Heres my DataService:
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Subscription, Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map'
#Injectable()
export class DataService {
constructor(private dataService: Http) {
}
urlprefix = 'http://123.123.123.123/api/v2/_table/';
api = '&api_key=7201521drgdc71';
getData(table, link, url): Observable<any> {
return this.dataService.get(this.urlprefix + table + link + url +this.api);
}
}
my app.routes:
import { provideRouter } from '#angular/router';
import { AnimalComponent } from './animal/animal.component';
import { AnimalDetailsComponent } from './animal/animal-details/animal-details.component'
{ path: '', component: HomeComponent },
{ path: 'animal', component: AnimalComponent },
{ path: 'animal/:link', component: AnimalDetailsComponent },
{ path: '**', redirectedTo: 'error404', component: Error404Component }
];
export const APP_ROUTES_PROVIDER = [
provideRouter(APP_ROUTES)
];
And my boot:
import { bootstrap } from '#angular/platform-browser-dynamic';
import { enableProdMode } from '#angular/core';
import { AppComponent, environment } from './app/';
import { HTTP_PROVIDERS } from '#angular/http';
import { APP_ROUTES_PROVIDER } from './app/app.routes'
if (environment.production) {
enableProdMode();
}
bootstrap(AppComponent, [APP_ROUTES_PROVIDER, HTTP_PROVIDERS]);
Chrome's Network indicates when I navigate back or forward on the same component between animal/:cat and animal/:dog via browser buttons, no new Http requests are made unless I change to a different component.
This is the last bug I'm down too. Would appreciate any help, thanks!

Resources