Next.js Fetching Data Inside Nested Child Component - javascript

Please consider my circumstance: In Next.js, I have built a component that is intended to be a child component that fetches data on its own (without any parent component) and now I have come to find this is not allowed by the authors of next.js. However, they mention the async-reactor library as a workaround:
May be you can try something like async-reactor
But I tried using async-reactor and was unable to render a fetch inside a nested child component in Next.js still. Here's what I tried:
// my child component
import React from 'react';
import {asyncReactor} from 'async-reactor';
import fetch from 'isomorphic-unfetch';
function Loader() {
return (
<div>
<h2>Loading ...</h2>
</div>
);
}
async function AsyncPosts() {
const data = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await data.json();
return (
<div>
<ul>
{posts.map((x) => <li key={x.id}>{x.title}</li>)}
</ul>
</div>
);
}
export default asyncReactor(AsyncPosts, Loader);
I expected this to work but it doesn't render anything except the word "Div" (which isn't even supposed to render "Div").
Is there a way to fetch within a child component in Next.js? Nothing I have tried so far worked but I find it hard to believe this is truly not possible.

As #Arunoda wrote:
We don't have plans to add support for calling getInitialProps in nested components.
The emphasis is on getInitialProps, you can make an ajax request inside any component, but know the benefits / drawback of it.
This ajax request will be implemented inside componentDidMount / useEffect hook which are not called at server-side.
One of the benefits can be lazy loading data, you don't need the entire page's data up front, that means less data => smaller network request.
One drawback can be that this section won't be passed to next's SSR mechanism, therefore won't be easily SEOed.

Related

calling setState only once inside of useEffect--is there a better method?

In my react app I use the following pattern quite a bit:
export default function Profile() {
const [username, setUsername] = React.useState<string | null>(null);
React.useEffect(()=>{
fetch(`/api/userprofiles?username=myuser`)
.then(res=>res.json())
.then(data => setUsername(data.username))
},[])
return(
<div>
{username}'s profile
</div>
)
}
When the page loads, some user data is fetched from the server, and then the page updates with that user data.
One thing I notice is that I only really need to call setUsername() once on load, which makes using state seem kinda excessive. I can't shake the feeling that there must be a better way to do this in react, but I couldn't really find an alternative when googling. Is there a more efficient way to do this without using state? Or is this the generally agreed upon way to load data when it only needs to be done once on page load
Without using any external libraries, no - that is the way to do it.
It would be possible to remove the state in Profile and have it render the username from a prop, but that would require adding the state into the parent component and making the asynchronous request there. State will be needed somewhere in the app pertaining to this data.
The logic can be abstracted behind a custom hook. For example, one library has useFetch where you could do
export default function Profile() {
const { data, error } = useFetch('/api/userprofiles?username=myuser');
// you can check for errors if desired...
return(
<div>
{data.username}'s profile
</div>
)
}
Now the state is inside useFetch instead of in your components, but it's still there.

React useEffect() hook highly affects SEO

I have a static website made with react that requests data from the backend in the useEffect() hook:
export default const App = () => {
const [data, setData] = useState("");
useEffect(() => {
server.get().then(data => {
setData(data)
})
})
return(
<title>{data}</title>
<h1>{data}</h1>
)
}
However, when Bing crawls the webpage, the following problem occurs:
Bing Screenshot:
<title></title>
<h1></h1>
How can I solve this issue?
React isn't used for static sites. If you'd like to have better SEO and server-side rendering you can use nextjs.
The way your app is setup currently will only return some HTML with and empty body to a GET request to / (which is what I suppose crawlers like the one you mentioned use) and starts rendering components after the JavaScript is loaded.
But if you decide on a server-side rendering approach, whenever a request is made to your app the server will first render the app on it's side and the return an HTML string with the rendered components.
Did you check if your server.get() is returning some data? I can't see any url here, so maybe it's actually returning nothing.
Even so, maybe you forgot to pass the second argument of useEffect, which is an array of arguments, which this hooks uses to trigger itself. For example, if you want to trigger only once, when component is mounted, you need to pass [] as second argument of useEffect.

useQuery after server-side rendering

I'm using next.js and apollo with react hooks.
For one page, I am server-side rendering the first X "posts" like so:
// pages/topic.js
const Page = ({ posts }) => <TopicPage posts={posts} />;
Page.getInitialProps = async (context) => {
const { apolloClient } = context;
const posts = await apolloClient.query(whatever);
return { posts };
};
export default Page;
And then in the component I want to use the useQuery hook:
// components/TopicPage.js
import { useQuery } from '#apollo/react-hooks';
export default ({ posts }) => {
const { loading, error, data, fetchMore } = useQuery(whatever);
// go on to render posts and/or data, and i have a button that does fetchMore
};
Note that the useQuery here executes essentially the same query as the one I did server-side to get posts for the topic.
The problem here is that in the component, I already have the first batch of posts passed in from the server, so I don't actually want to fetch that first batch of posts again, but I do still want to support the functionality of a user clicking a button to load more posts.
I considered the option of calling useQuery here so that it starts at the second "page" of posts with its query, but I don't actually want that. I want the topic page to be fully loaded with the posts that I want (i.e. the posts that come from the server) as soon as the page loads.
Is it possible to make useQuery work in this situation? Or do I need to eschew it for some custom logic around manual query calls to the apollo client (from useApolloClient)?
Turns out this was just a misunderstanding on my part of how server side rendering with nextjs works. It does a full render of the React tree before sending the resulting html to the client. Thus, there is no need to do the "first" useQuery call in getInitialProps or anything of the sort. It can just be used in the component alone and everything will work fine as long as getDataFromTree is being utilized properly in the server side configuration.

loading data into vuex store before app loads, how to accomplish this?

I am making a dispatch call to my store inside the created hook of App.vue, in a child component I then ask for that with a getter, the issue seems to be that when loading the app the child component is loaded before the data has been placed in the store and does not display. I am confident about this from the fact that I console logged and the first log is the child component who is the consumer of the store. How can I guarantee that the dispatch which is needed site wide happens before any other components are loaded?
// App.vue
created() {
this.$store.dispatch(this.$mts.diseases.DISEASES_LIST) //note I tried with async/await to no avail
...
//child component
created() {
this.diseases = this.$store.getters.diseasesList
...
As noted I tried to make the code inside the App.vue asyn but it seems that's it's not loading first so this did not help.
You should put the property inside a computed in your child component, that way it will populate as soon as the value exists in your store
computed: {
diseases () {
return this.$store.getters.diseasesList
}
}
See the VueX docs
If you want to wait for the data to be available before loading the component then you can use v-if see docs
<your-component v-if="$store.getters.diseasesList">
...
</your-component>
Consider using Nuxt.js (https://nuxtjs.org/) it has fetch and asyncData support out of the box, so that component won't render before the promises they return are solved.

Does React Router necessarily complicate state management (without Redux)?

I'm fairly new to React to trying to wrap my head around routing via React Router while also passing required data to components. I will probably eventually incorporate Redux in my app, but I'm trying to avoid it initially.
It seems like using React Router as opposed to serving individual pages from the server means having to store state data in the App.js component since that's where the Router exists.
For example if I'm on site.com/x and I want to navigate to site.com/y and /x looks like this:
<div>
<XOuter >
<XInner />
</XOuter>
</div>
And App.js looks like this:
<BrowserRouter>
<Route exact path="/x" component={X} />
<Route exact path="/y" component={Y} />
</BrowserRouter>
... if the GET request is being called from XInner and the results will inform the content of /y, XInner will have to pass the response all the way back to App.js to properly render /y.
It seems like this could get messy quickly. Is there any way to avoid it?
This isn't as bad as you think, for two reasons:
If you use React Router's <Link> component to create links instead of using <a> directly, it will add event handlers that cancel the link's actual navigation and instead use history.pushState to do the navigation. To the user, they think they're on the new page (the URL bar shows this), but no GET request ever actually happened to load it.
React Router's paths are parsed via path-to-regexp. This lets you add parameters to the URL and then extract them from the router's props. You can also put data in the query string and then parse it later. This will let you pass state from one page to another without using any top-level React state, with the added benefit of making the browser's history and URL copying automatically work right.
The data is stored in the path instead of App.js. Path should be converted to props through pure function so the same path is always converted to the same props. That's the external state that chooses a <Route /> and sets its props.
Root of your problems lies in this design:
if the GET request is being called from XInner and the results will inform the content of /y, XInner will have to pass the response all the way back to App.js to properly render /y
Remove the if the GET request is being called from XInner... and all your concerns become moot.
Component A should not be responsible for fetching data for Component B. If /y needs data, fetch the data in Y's componentdidmount.
Example code showing the concept
fetchData(){
fetch(...) // or axios or whatever
.then(() => {
this.setState({
data: 'Hello World'
})
})
}
componentDidMount(){
this.fetchData()
}
render() {
return(
<div>
{this.state.data}
</div>
)
}

Categories