Wait _app.js loaded then run component on Next.js - javascript

I'm using Next.js to develop a website.
I need to use the JavaScript SDK to connect the user login.
I decided to init the SDK in _app.js because I think that It should be the first file the server load.
so I wrote these code in _app.js
componentDidMount () {
window.mySDK = new userInfoSDK()
console.log('_app')
}
and wrote something like this in page.js
async componentDidMount () {
console.log('page')
const loginStatus = await window.mySDK.getInfo()
}
and I get the result is window.mySDK is not defined
The console shows
page
_app.js
so that mean the page.js component is mounted before the _app.js?

According to React lifecycle componentDidMount run after render. Saying that, it means it run the render first and then componentDidMount.
Simple solution:
in _app.js write your code in constructor:
constructor(props) {
super(props)
console.log('_app')
}
You don't need to change anything in page.js.
in this case, the _app run first and then other pages.
the output will be
_app.js
page

ComponentDiDMount is invoked once, only on the client (not on the
server), immediately after the initial rendering occurs. At this point
in the lifecycle, you can access any refs to your children (e.g., to
access the underlying DOM representation). The componentDidMount()
method of child components is invoked before that of parent
components.
I think for your use case you can initialize your SDK on another REACT hook or in constructor to make sure it will be executed before.

Related

Load undefined component via ajax with vue3 after app instancing?

I would like to know which is the way to load an new component inside vue3 app instance. As far as I know its only possible to use components predefined during createApp() or via some internal trickery even after initialization but never on runtime after use.
The problem is than I cant find a way to fetch the component at runtime, via an ajax call so instead of throwing "Failed to resolve component: mycomponent" it would check the server and import the component.
Yes, I know about defineAsyncComponent and vue3-sfc-loader but none of them seem to handle undefined components. They all seem to require the definition of all the components that we will be using. Or no?
var vapp = Vue.createApp({
template: '<mycomponent></mycomponent>',
components: {} /** not defined at runtime **/,
_importUndefinedComponent: function(tagname) {
$.get('/components/' + tagname + '.js');
}
});
For now I think that it's possible to edit the internal workings of Vue, as it seems that vue already uses promises to load async components....
A usecase for dynamic components. I have an crud system with hundreds of components. I want to make quick prototypes. So this way all I have to do is just upload the component to the right folder an use it. No build step and no fancy stuff. All components are using options api. So basically it's just an Object which I will eval.

How do you avoid extra React component renderings when using useEffect hook?

everyone, I am currently working on a React/Electron project and am kind of stumped on how to meet my client's requirements of having less renders when using the useEffect hook. In my current project, I am using a container/component structure so I have my index.js file that contains all the logic for the component and the useEffect in question. The useEffect in the index.js is intended to pre-populate a file input if the file exists, however, this is what is causing the extra render since the component is rendering before the useEffect is finished and then once it is finished the home component then re-renders again with the updated data. So my question is is there a way to have the useEffect finish before home component renders the first time or is this just a part of React that cannot really be changed and my client will have to accept?
useEffect(() => {}, [])
Empty array at the end means this useEffect doesn't have any deps so it will run only once at the beginning.
ref: https://reactjs.org/docs/hooks-reference.html#useeffect (yellow note below)

Run function AFTER route fully rendered in Nuxt.js

Background:
I'm building an SSR website using Nuxt. I want to run a script to fix some typography issues (orphaned text in headers). I can't do this UNTIL AFTER the DOM is rendered. How can I implement this function once so it runs after each page's DOM is rendered? It can be either in the Router or in a Nuxt Layout, or elsewhere.
What I've tried:
In my layout.vue, Mounted() only runs on the first load (as expected) and adding $nextTick doesn't seem to affect that. This is even true for generated static pages served from a real webserver.
In my layout.vue, using Vue's Updated() never seems to fire. I assume this means Nuxt is getting in the way.
Using app.router.afterEach() the function runs on each route change (including first load), but way before the DOM is rendered making it worthless.
If I add Vue.nextTick() into the .afterEach() the function runs on the current page JUST BEFORE the route changes (you can see it flash) but DOES NOT run before that.
What works but seems dumb:
Putting the function in the Mounted() block on each page.
mounted: function(){
this.$nextTick(function () {
const tm = new TypeMate(undefined, { selector: 'h2, h3, p, li' });
tm.apply();
})
},
But this seems like a bad idea especially as we add pages. What am I missing? Is there a smart way to do this? Nuxt's documentation is next to useless for some of this stuff.
You can create mixin with mounted function. Lifecycle hooks from mixin will be merged with your lifecycle events and each will be run.

Empty result at fetch request with ssr rendring

I'm need you suggestion how implement load a items by API and server side rendering . My ssr is work with help express and babel. I have this component:
class MyApp extends Component {
constructor(props) {
super(props)
this.state = {result: []}
}
componentDidMount() {
//request to api and set result in state
}
render() {
return (<div>{this.state.result}</div>)
}
}
I always get an empty component when rendering. How to make it rendered only after get the data from Api. My render is work by example: https://medium.com/styled-components/the-simple-guide-to-server-side-rendering-react-with-styled-components-d31c6b2b8fbf Thanks
None of the react component lifecycle hooks will block rendering, which you need to ensure data fetching finishes before rendering, to get SSR. There are libraries that can help with this depending on your data management.
redux-connect is one, which lets you define blocking promises in a asyncConnect decorator.
react-data-fetching-components is not redux specific and lets you define blocking promises in withInitialData
react-ssr is similar, with a fetchData static method.
Next.js is also a popular framework that does SSR out of the box with minimal configuration.
There might be a way to do this with React's built in APIs now, but I'm not sure. In general you need to add your own blocking data fetching abstraction on the server.

How are multiple Components implemented?

I want to separate out the logic of my app which needs to call an OData service before the main execution can continue. I have other apps which need this behaviour implemented in the future, so if I can modularise that functionality into a component, it would be very useful.
I have Component.js for the main app, and I'd like to add a second component to be run first, which then loads the main component once the OData result has been received.
How do I load a Component, then get that Component to run the next one (in this case a UIComponent)?
It seems the sap.ui.component code automatically appends "Component.js' to the end of the name provided, so how do you have different Component files with different names?
var oComponent = sap.ui.component({
name: "MYAPP.Component2",
id: "componentId"
});
Returns error,
failed to load 'MYAPP/Component2/Component.js' from ./Component2/Component.js: 404 - NOT FOUND
Could anyone provide some example code of a UIComponent having a dependency of a Component, and the file structure of that part of the application?
You can build multiple components as separate entities and then have them listed as dependent components inside a master component for your project. In your main or master component you can list these secondary components under the metadata config's dependencies array. Each component is atomic to itself so each will have its own Component.js with routes and view path. We create nested components in this same manner and it works really well.

Categories