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

I have an empty array that needs to be filled with numbers

Currently, I am facing a challenge where I have an empty array and need to insert numbers from 1 to 20 into it. Once that is complete, the next step is to calculate the total sum of all these numbers. The stumbling block I am encountering lies in this sect ...

Extracting numbers using regular expressions can be tricky especially when dealing with mixed

Currently, I am attempting to create a javascript regex that can extract decimal numbers from a string containing a mix of characters. Here are some examples of the mixed strings: mixed string123,456,00indeed mixed string123,456.00indeed mixed string123,4 ...

Leverage the power of dynamic PHP variables within your JavaScript code

I have an image database and a search form. I want to display the images on the next page using JavaScript with the OpenLayers library. Here is the PHP code I wrote: <?php mysql_connect('localhost','root',""); mysql_select_ ...

My current array is arr=[1,2,3,4]. I recently added an element to it using arr.push(5). Now I want to rearrange the array to be [5,4,3,2,1]. Any suggestions on how to achieve this

I currently have an array in the following format: var arr = [1,2,3,4] // Add another element to the array arr.push(5) // Now, arr = [1,2,3,4,5] I want to print my array as The elements in the array arr are: 5,1,2,3,4 When I use Arr.reverse(), it retu ...

Ionic 3 Storage Timing Explained

I have a scenario where I am trying to load JSON data from storage and display it on the HTML template of my page. However, when I try to do this, I encounter errors suggesting that the information is not yet available upon entering the page. I'm sta ...

Exploring the use of ngResource in conjunction with HttpBackend - Potentially unreached rejection issue

Issue Currently, I am working on testing a controller utilizing Karma, Mocha, Chai, and PhantomJS as part of the testing process. IndexCtrl.js (simplified) app.controller('IndexCtrl', ['$scope', '$resource', function($scope ...

What is the best way to iterate through an array of objects in a react component?

I need help figuring out how to iterate through the array of objects in my React code. Currently, I am using getStaticProps() to fetch data from a mock API server online. My project is built with nextjs. How can I achieve this using loops like for or whi ...

Is it redundant to use flatMap in RXJS?

I recently came across an enlightening article on RXJS which delves into the concept of flatMap. After understanding its purpose - to flatten observable of observables into a single observable sequence (similar to SelectMany in C#) - I noticed an interes ...

Using Javascript, send text from a textbox to an ActionResult in ASP.NET MVC using AJAX

Html <input type="password" id="LoginPasswordText" title="Password" style="width: 150px" /> <input type="button" id="LoginButton1" value="Save" class="LoginButton1Class" onclick="LoginButton1OnClick" /> Json var TextBoxData = { Text: Login ...

Experiencing difficulty adding material-ui to my React project

click here to see the image descriptionAfter pasting npm install @material-ui/core in my root directory, I encountered the following output: I decided to enhance the user interface of my application by incorporating material-UI for the first time. ...

Is there a way to apply an event function after adding elements through append?

When I click the button, a div is appended inside the body. However, I am trying to make it so that when I click on this newly appended div, an alert message pops up. I have tried implementing this with a highlighted area, but have been unsuccessful. How c ...

The sequence of elements within a React.addons.createFragment object

Currently, I am exploring the documentation on creating fragments in React from https://facebook.github.io/react/docs/create-fragment.html. It appears that the engineers at Facebook place a significant emphasis on the object memory layout, specifically the ...

The number I clicked is not displaying on the screen in my React project

When attempting to display the clicked number on the screen, it is not appearing. However, it does show in the console. I am unsure of how to fix this issue; the number should be displayed on the screen next to "Number:" import { render } from "@testing-li ...

Executing a JavaScript function across multiple elements: A step-by-step guide

I recently came across this code snippet on w3schools.com: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * {box-sizing: border-box} body {font-family: Verdana, ...

The quickest method to modify the anchor element's class depending on the query string

Requirement - I aim to accomplish this task using only pure JavaScript without any additional libraries, although I am open to using one if necessary. I need to assign an extra class to anchor elements that contain a query string of 'xyz=negate' ...

Guide on effectively managing props within a single component in React Navigation

When attempting to navigate from my App component to the GamePlay component, I encountered an issue. Here is a snippet of my App.js: import React from 'react'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; imp ...

What exactly is the purpose of the colon in JavaScript's import statement?

Looking at the following example. import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database' I am puzzled by the use of colons and I am unsure about where the imported files are being referenced from. ...

Guide to extracting the outcomes of a promise array and populating them into a new array using Protractor

I am facing a challenge with transferring data from an array of promises generated by the following code: element.all(by.repeater('unit in units')). It seems to be difficult for me to store this data into another array: element.all(by.repeater(& ...

What methods can I use to minimize the frequency of the blue box appearing around text?

I successfully developed code that enables user interaction with text, triggering the opening of a modal box when clicked. In this modal box, the text turns red upon clicking, indicating activation of a checkbox. However, I notice that every time I intera ...