Every time I navigate to a new page in NextJs, the useEffect hook

I am working on developing a new blog app with Next.js.

In the current layout of the blog, I have successfully fetched data for my sidebar (to display "recent posts") using the useEffect/fetch method, as getInitialProps only works on Pages. However, this causes the data to reload every time I switch between pages, resulting in a momentary blank screen and post title reloads.

Is there a way to prevent this behavior after the initial load and maintain a constant or something similar? I tried using the "[]" method but it didn't solve the issue:

  const [posts, setPosts] = useState([])

  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch('/api/posts');
      const {data} = await res.json();
      setPosts(data)
    }
    fetchData()
  }, []);

Alternatively, is there a better approach to fetching data for my sidebar? This solution I implemented is functional but not without its drawbacks.

Answer №1

import { useState, useEffect } from 'react'


export default function RightBar() {

  const [posts, setPosts] = useState([])

  useEffect(()=>{
    const fetchLatestPosts = async () => {
      const response = await fetch('/api/posts');
      const {data} = await res.json();
      setPosts(data)
    }
    fetchLatestPosts()
  }, []);


    return (
      <div className="rightbar content">
        <div className="rightbarContent">
          <h3 className="sidebarborder"><span className="sidebarheader">Recent Posts</span></h3>
          {posts.slice(0,5).map(singlePost => {
              return (
                <div key={singlePost._id}>
                    * <Link href={`/${singlePost._id}`}>{singlePost.title}</Link>
                </div>
              )
          })}
          <h3>Categories</h3>
          <p>blabla</p>
        </div>      
      </div>
    )
  }

The structure of the component is as follows:

Layout > Header Topnav Main Footer

Main has two children - LeftBar (containing main content) and RightBar (displaying recent posts)

Layout wraps the index.js page, passing props.children to layout > main > leftbar components.

I hope this explanation is clear enough for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to combine multiple Apollo queries within the state using React?

Recently, I started working with React, Apollo, and MongoDB. However, I am encountering a specific issue that I need help with: In my application, I have a table that consists of three columns (ID - ID_A - ID_B) and I executed a query that returned an arr ...

Error Encountered with Next.js 13.4.1 when using styled-components Button in React Server-Side Rendering

I am currently working on a React project using Next.js version 13.4.1 and styled-components. One problem I'm facing is with a custom Button component that I've created: import React from 'react'; import styled from 'styled-compone ...

Display the outcome of a POST request on the webpage

Currently working with node.js/express and have a view that includes a form. This form POSTs to a route which returns JSON data. I want to be able to submit the form and display the returned data underneath the form on the same view without refreshing the ...

Transform the JSON response from MongoDB into a formatted string

var db = mongoose.connection; const FoundWarning = db.collection('warning').find({UserID: Warned.user.id, guildID: message.guild.id}).toArray(function(err, results) { console.log(results); }) I have been attempting to ...

How to Ensure an Element Appears Above Another Despite Z-Index Troubles?

After conducting approximately 2 hours of research on this topic, I was unable to find clear answers or solutions. Hence, I have decided to address the issue here. The problem I'm facing is as follows: Due to the nature of HTML/CSS, it seems impossi ...

Prevent JavaScript from sending a POST request to a specific URL

Currently facing Cross Site Scripting (XSS) vulnerabilities in a web application, I am curious if there are security measures equivalent to Content-Security-Policy: frame-ancestors and X-Frame-Options for JavaScript. My objective is to restrict the abilit ...

"Enhancing user experience with dynamic input fields through Ajax auto-fill functionality

I have a unique invoice form that allows users to add multiple parts at their discretion. As the user inputs a part number, an AJAX script automatically populates the description and price fields. The script functions properly for the initial input fields ...

Having trouble with running npm install after updating node js?

Images displaying error messages First Image Second Image Third Image Version of Node.js ...

Running JavaScript function from AJAX response containing both HTML and JavaScript code

For my first time using AJAX to prevent page refresh upon form submission, everything works flawlessly. The data is received in HTML form and placed into the designated div. However, I am encountering an issue with one of the JavaScript functions responsib ...

Test failed due to missing Jest mocked data acquisition

Having an issue with my component that is supposed to load data from an API, but the test cannot find the element containing the data as it is mocked for testing purposes. component: import { useDispatch, useSelector } from "react-redux"; import ...

Sort Messages By Date Created

While using Vue, I encountered a general JavaScript question. I am fetching cat messages from an API for a chat interface. The initial call returns an array of objects where each object represents a chat message: data: [ {id: 1, created_at: "2022-05 ...

Is the Webpack vendors JS bundle in Vue CLI containing unlisted code that is not in the dependencies or package-lock.json file?

An information security auditing tool flagged an outdated library with known vulnerabilities in our webpack-bundled chunk-vendors.js file generated using Vue CLI: The library in question is YUI 2.9.0. It appears that this library is not fully included, a ...

Discovering the largest element within a group to establish the height for the rest

There is a component mapping card elements that look like this: https://i.stack.imgur.com/CktsE.png The topmost, leftmost card appears to be missing some height compared to others. Is there a way to determine the height of the tallest components and then ...

How can I modify the URL path using react-i18next?

I've been grappling with this problem for the past few days. My React app is causing me some trouble as I try to implement multilingual support using i18next. I aim to modify the URL path based on the selected language, such as http://localhost:3000/e ...

Load images easily using jQuery

I am experiencing a small problem. I am attempting to display an image, but it doesn't seem to be correct. Although I am able to retrieve the data of the image, my goal is just to display it instead. What could be causing this issue? var imageUrl = ...

Switching sub components based on routing through navigation links after logging in

I'm having an issue with my routing setup while transitioning from the login page to the main page. Here's how my Routes are structured: App.jsx <BrowserRouter> <Routes> <Route path="/main/" element={<Main ...

Error: express is missing a closing parenthesis for the argument list

When running this code in the VS Code terminal, be sure to verify any errors that may occur. var express = require('express'); var app = express(); app.get('/', function(request, response) { response.send("hello world"); }); app.li ...

Is there a way to convey a function existing on the Server Component to the Client Component?

Seeking assistance with NEXTJS 13 'app Dir' Is there a way to transfer a function from the Server Component to the Client Component? I have a Button as my Client component and it is wrapped by another Server Component. I want the Button to exec ...

Utilizing children as a prop within a Vue component

In React, I can create a FancyList component like this: const FancyList : React.SFC<{},{}> ({children}) => ( <ul> {...children} </ul> ); const FancyListItem : React.SFC<{text: string}, {}> ({children}) => < ...

Struggling to spot my error (codewars, javascript, level 8)

Can You Translate?! After receiving a message on WhatsApp from an unfamiliar number, you wonder if it's from the person with a foreign accent you met last night. Your task is to write a simple function that checks for various translations of the word ...