Angular 2 Router strange null call - wordpress

Problem
Im loading some menu items from the Wordpress Rest API, then navigate to the page/:id with the correct id of the wordpress page. Everything works fine except of that:
Early when my page is loading I get this null call in the network section of the chrome developer. This is locally, on my server its also a 404 NOT FOUND.
Setup
Angular 2 + Typescript (Angular 2 RC2, Router 3.0.0-alpha.6)
Wordpress REST API
Code
Template
<header></header>
<router-outlet></router-outlet>
<footer></footer>
Routing
export const routes: RouterConfig = [
{ path: '/page/:id', component: PageComponent },
{ path: '/page/home', component: PageComponent, index: true }
];
Header.ts
this.myService.getNavigation()
.subscribe(
menuItems => {
this.menuItems = menuItems;
this.router.navigate(['/page', this.menuItems[0].title]);
},
error => this.errorMessage = <any>error);
Main.ts
bootstrap(AppComponent, [
...APP_ROUTER_PROVIDERS,
...HTTP_PROVIDERS,
...ROUTER_PROVIDERS,
...ENV_PROVIDERS,
{ provide: LocationStrategy, useClass: HashLocationStrategy }
])
Assumption
I guess it has something to do with my routing setup. When I comment out the <router-outlet> it does not happen, everything else works good.
Question
What is this strange call at /null and how can I avoid it?

I guess you have somewhere <img [attr.src]="var"> or similar.

Related

nextjs reload page with Link component

I have a simple nextjs 13 application (appDir) with 2 pages and a <Link/> component navigation.
first page Home - static
second page Test - receiving dynamic random content on the server side (fetch) from a third-party source.
Problem: When the application is rendered everything works fine, but when I try to switch between pages, my test page shows the old content, I can refresh the browser to get the actual data, is very similar to navigating through regular links <a/>, but i need without reloading the entire application.
Q: How can I force nextjs 13 to reload the Test page when I switch between pages with <Link/> component?
// src/components/navbar.tsx
'use client'
import {usePathname} from "next/navigation";
import Link from "next/link";
const navItems = [
{text: 'Home', href: '/'},
{text: 'Test', href: '/test'}
];
const Navbar = () => {
const pathname = usePathname();
return <nav className="nav nav-masthead justify-content-center float-md-end">
{navItems.map((item: { text: string, href: string, link?: boolean }, idx: number) => (
<Link key={idx} href={item.href} className={`nav-link${item.href === pathname ? ' active' : ''}`}>
{item.text}
</Link>
)
)}
</nav>
}
export default Navbar;
// src/app/test/page.tsx
import * as crypto from "crypto";
const getData = async () => {
const res = await fetch('http://localhost:3000/random-data', {cache: 'no-store'});
if (!res.ok) {
throw new Error('Failed to fetch data');
}
return res.json();
}
export default async function Page() {
return <p>{crypto.createHash('sha256').update(JSON.stringify(await getData())).digest('hex')}</p>
};
I've recently asked about this same topic on their feedback discussion on github: https://github.com/vercel/next.js/discussions/41745?sort=new#discussioncomment-4620262
The cause of the problem is Link is only doing client side navigation and seems to serve a cached state of the previously visited component. You'll notice that the client never calls back to the server and thus the server component never runs the second time.
I've been searching for days, but haven't found a way to force Link to reload or force refresh the component to re-render.
My conclusion is that if you have dynamic data that needs to refreshed periodically, it's best to render it in a client component and not use a server component for now.
Also, if you'd like to use Suspense, you'll need to use a library like SWR or React Query for any client side data fetching.

How to route to different components in Vue router based on query param

I'm using firebase for user authentication. Except for login/signup flows there are 3 flows called email actions - these include reset password, recover email and verify email.
You can customize the URL that Firebase is calling you, but it has the be the same URL for all actions, while the actual action is passed as query param. Here's an example:
https://example.com/usermgmt?mode=resetPassword&oobCode=ABC123&apiKey=AIzaSy...&lang=fr
// ^^^ from here on starts the dynamic part
My question - how can I use Vue router to load different component based on mode query param?
I know I can create a single component that will dynamically load one of the other 3 based on the query param, but I'm looking for a cleaner way.
I tried looking for "Vue router based on query params" and only found examples how to pass query param into the component as a prop.
Also looked for examples of implementation of Firebase authentication in Vue, but all of the examples focus just on login and signup.
EDIT:
Right now I have a router with this config:
{
path: '/auth/actions',
component: () => import('pages/EmailActions.vue'),
props: (route) => {
return {
mode: route.query.mode
}
}
}
Then, inside EmailActions I have to dynamically show one of 3 components based on mode props.
This file is really redundant as it only contains routing code.
What I'd really like to do is something like this in the router config:
{
path: '/auth/actions',
children:[
{
query: {mode: 'resetPassword'},
component: () => import ('pages/ResetPassword.vue')
},
{
query: {mode: 'recoverEmail'},
component: () => import ('pages/RecoverEmail.vue')
},
{
query: {mode: 'verifyEmail'},
component: () => import ('pages/VerifyEmail.vue')
}
]
}

WordPress + Gatsby Custom Rest Route Not Showing in GraphQL

I'm fairly new to Gatsby and Im trying to build a site using WP as the content provider. I have a custom rest route built in WP
wp-json/lbt/v1/settings
and right now its just returning
{
"time_and_location": "Testing"
}
I cant seem to find out how to get that route to be available in graphQL for my Gatsby site. I have it set in my includedRoutes as
includedRoutes: [
'/*/*/categories',
'/*/*/posts',
'/**/lbt/**',
'/*/*/events',
'/*/*/pages',
'/*/*/media',
'/*/*/tags',
'/*/*/taxonomies',
'/*/*/menus'
],
I also see this when I spin up Gatsby
-> wordpress__lbt_v1 fetched : 1
-> wordpress__lbt_settings fetched : 1
I've searched a lot of different sites, but I haven't managed to find anything. Any help appreciated.
you need to add custom normalizer in "gatsby-config.js"
like
...
plugins: [
.....,
{
resolve: "gatsby-source-wordpress",
options: {
......
normalizers: normalizers => [ mapCustomApis,...normalizers],
}
}
......
add the "mapCustomApis" normalizer like
const mapCustomApis = {
name: `mapCustomApis`,
normalizer: function({ entities }) {
return entities.reduce((acc, e) => {
return acc.concat(e);
}, []);
}
}
i replicated the code from https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-wordpress/src/normalize.js#L102
to support my custom Apis response
make sure your normailzer is before the rest of the normalizers

Next.js Amplify Serverless AppSync graphql (Amplify error)

I'm trying to create an App that uses Amplify and AppSync with Next.js.
I was able to deploy the application successfully but when I'm trying to access the application (trying to fetch data from AppSync) It is failing.
I'm kinda lost what needs to be looked at, the application seems to be working fine locally but when I'm publishing it on AWS it is failing.
I'm getting error: TypeError: Cannot read property 'getName' of undefined
//quotes.js
import { Connect } from 'aws-amplify-react';
........
<Connect
query={graphqlOperation(queries.getName)}
subscription={graphqlOperation(subscriptions.onCreateName)}
onSubscriptionMsg={(prev, { onCreateName }) => ({
...prev,
getName: {
...prev.getName,
items: [
...prev.getName.items,
onCreateName,
],
},
})}
>
Has anybody come across such an issue or any idea to resolve the issue? Thanks in advance.
Running the subscription when doing SSR is not needed / useful and requires a WebSocket client in the server, you can try Dynamic Imports with no SSR to have the subscription only happen on the client. (using { ssr: false })
import dynamic from 'next/dynamic';
const DynamicComponentWithNoSSR = dynamic(() => import('../components/hello3'), { ssr: false });
function Home() {
return (
<div>
<Header />
<DynamicComponentWithNoSSR />
<p>HOME PAGE is here!</p>
</div>
);
}
export default Home;

Angular2 routing: canDeactivate limitations

I've got a form in angular2. If it's dirty (with unsaved changes), I want to restrict the user from navigating away.
Research shows that the canDeactivate route guard is the way to do it.
Google led me to this github file which seems to implement what I want.
import { CanDeactivate } from '#angular/router';
import { FormGroup } from '#angular/forms';
export interface FormComponent {
form: FormGroup;
}
export class PreventUnsavedChangesGuard implements CanDeactivate < FormComponent > {
canDeactivate(component: FormComponent) {
if (component.form.dirty)
return confirm('You have unsaved changes. Are you sure you want to navigate away?');
return true;
}
}
Now, I've put this service in my project, injected it in my form component, added it to my routing module as so...
const routes: Routes = [{
path: '',
loadChildren: 'app/main/main.module#MainModule',
canActivate: [AuthenticationGuard],
}, {
path: 'login',
component: LoginComponent,
canDeactivate: [PreventUnsavedChangesGuard]
}, ]
and included it in the app module's providers array.
Now, it seems to work. In case I have unsaved changes when I click the browser's back button. I get the confirmation dialog. However, when I input a new URL in the address bar, I don't get the confirmation. Also, I'm able to close the tab when I have unsaved changes.
Are these known limitations of canDeactivate, or am I doing something wrong. How do I get the behavior I want? (Confirmation dialog if the user attempts to close tab or navigate away using the address bar?)

Resources