Using Redux with Next.js to implement getStaticPaths

Can someone help me understand how to implement getStaticPaths in conjunction with Redux in Next.js?

I'm currently using next-redux-wrapper to manage my content, but I am encountering issues when trying to display the data.

Below is a snippet of my code for reference:

import { useSelector } from "react-redux";
import {getPageData} from '../redux/actions/pages'
import { useRouter } from "next/router";
import {wrapper} from '../redux'
import { getNavItems } from '../redux/actions/navItems';
import { getServiceData } from '../redux/actions/services';
import { getHomePage } from '../redux/actions/homePage';

export default function pageTemplate({page}) {
  return(
    <h1>{page.title}</h1>
  )
}

export const getStaticPaths = async () => {
  const pages = await getPageData()

  const paths = Object.keys(pages).map((key) => {
    const page = pages[key]

    return{
      params: {slug: page.slug.current}
    }
  })

  return{
    paths,
    fallback: false
  }
}

export const getStaticProps = wrapper.getStaticProps((store) => async (context) => {
  await store.dispatch(getHomePage());
  await store.dispatch(getServiceData());
  await store.dispatch(getNavItems());
 
  const slug = context.params.slug

  console.log(slug)

  const page = await store.dispatch(getPageData(slug))
  return {
      props: {page},
      revalidate: 60
  };
}

In addition, my redux action seems to be functioning properly as tested in the sanity.io groq playground.

import * as actionTypes from '../actions/actionTypes';
import { groq } from 'next-sanity';
import { getClient } from '../../lib/sanity.server';

export const getPageData = (slug) => async (dispatch) => {
  const query =  groq`
  *[_type == "page"]{
    _id,
    title,
    slug
    
  }
  `;
  
  const queryTwo =  groq`
  *[_type == "page" && slug.current != $slug]{
    _id,
    title,
    slug
    
  }
  `;

  if(slug) {
    try {
      // const client = ...
  
      const pageData = await getClient().fetch(query);

      dispatch({
        type: actionTypes.GET_ALL_PAGES,
        payload: pageData
      });
    } catch (err) {
      console.log(err);
    }
  }

  try {
    // const client = ...

    const pageData = await getClient().fetch(queryTwo);

    dispatch({
      type: actionTypes.GET_ALL_PAGES,
      payload: pageData || pagesData
    });
  } catch (err) {
    console.log(err);
  }
};

Answer №1

Dealing with a similar issue in the past, I discovered that you can utilize getStaticPaths without relying on the next-redux-wrapper.

Here's an example snippet from some recent work I've been doing:

import { ReduxWrapper, store } from '@store/store'

export const getStaticPaths = async () => {

  const postsSlugs = store
    .getState()
    .posts.posts.map((post) => ({ params: { slug: post.slug } }))

  return {
    paths: postsSlugs,
    fallback: true,
  }
}
export const getStaticProps = ReduxWrapper.getStaticProps(
  (store) => async (context) => {
    const slug = context.params?.slug
    const post = store.getState().posts.post
    return {
      props: { post },
    }
  },
)

I trust this information proves helpful to you or anyone else facing a similar challenge.

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

Verify the alignment of an element in the middle using React

Currently working on a carousel feature and aiming to highlight the element positioned in the middle of the slider. This will help draw attention to it. https://i.stack.imgur.com/NB9xB.png Any suggestions on how I can target this specific component? While ...

Even though the onSubmit attribute is set to false in the HTML form, it still submits

I've been struggling with a form that just won't stop submitting, no matter what I do. I have checked similar questions on SO, but none of the solutions seem to work for me. It's frustrating because it's such a simple task. The reason w ...

Dealing with the issue of needing to include "%20" in the URL after receiving a NextJS build

Currently, I am working on a simple NextJS (v13) project utilizing TheMoviedb API. I am fetching images and titles of content with an API request in this project. The image paths can be accessed using a variable named dt, which corresponds to either backdr ...

How can you conceal an HTML element when the user is using an iOS device?

I need the code to determine if a user is using an iOS device and, if not, hide the HTML input type "Play" button. So, I'm uncertain whether my iOS detection is correct, the hiding of the "Play" button in the code, or both: <!DOCTYPE html> < ...

How do you go about installing the most recent version of a module through Private NPM?

When using a private npm registry, I have noticed that some common commands do not seem to be functioning properly: npm install without specifying a specific @version :: issue npm outdated :: issue npm update :: issue npm view <private-packag ...

Unable to transform into a tangible entity

When I run the code below, I encountered an error stating: Uncaught exception: TypeError: Cannot convert 'validation.messages.field' to object $.fn.validate = function(validation) { $.each(validation.rules, function(field, fieldRules){ ...

Search for Azure Time Series Insights (TSI) data insights

Is there a way to access real-time data from Azure TSI using the TSI query API? I am currently utilizing the TSI JavaScript Client library, which provides two wrappers for the Query API. However, these wrappers only allow me to retrieve aggregate data li ...

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

Material design Snackbar notification smoothly glides onto the screen

https://i.stack.imgur.com/yJDVj.png Hello there! I am currently working on a fun project using React and Material-ui. However, I'm facing an issue when the snack bar or react-toastify pops up. It doesn't stay on the screen (RED: scroll up/dow ...

What is the best way to isolate the elements from the specified dictionary that contain valid data?

I need to extract only the data for Flipkart from this array and create a new array containing just that information. json = [ { "amazon": [] }, { "flipkart": { "product_store": "Flipkart", ...

Guide to transforming an embed/nested FormGroup into FormData

Presenting my Form Group: this.storeGroup = this.fb.group({ _user: [''], name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])], url_name: [''], desc: ['', Validators.compose([Valida ...

Exploring GatsbyJs: Optimal Strategies for Storing Strings and Text on Static Websites

Currently in the process of building a website using Gatsby JS and Material UI. I'm wondering about the best approach for storing the site content. This website will serve as a promotional platform for a small business. Should I store the text direct ...

The color scheme of the header in Material UI Tables

I am facing a challenge in customizing the mui TableHeader with a dark background. Despite trying to use @mui/styles, I have been unsuccessful due to React version 18 restrictions. Can anyone offer suggestions on how to achieve this? https://i.stack.imgu ...

Activate click events when button is being held down

I'm currently working on a directive that shifts an element to the right whenever clicked. However, I want the element to keep moving as long as the button is pressed. .directive("car", function(){ return { restrict:"A", link:func ...

Difficulty encountered while attempting to deploy the front-end on Heroku

I recently completed a typeorm project with the following structure: https://i.stack.imgur.com/ReQK1.png Both the client and root directories contain index files located in the src directory. In the package.json file within the client directory, I made a ...

NPM Dependency Error

Attempting to launch the app [surveyman][1] has been a challenging endeavor. When running the $npm run start command, the following log is returned: 0 info it worked if it ends with ok 1 verbose cli [ 'C:\\Program Files (x86)\&bso ...

Use Jquery to add unique styles to specific words within a paragraph

I am looking to specifically style a particular word within a dynamic div for example, <div id="info">{$info}</div> prints <p>here you can get info about somnething. if you want more info about something then click here....</p> ...

What are some effective methods to completely restrict cursor movement within a contenteditable div, regardless of any text insertion through JavaScript?

Recently, I encountered the following code snippet: document.getElementById("myDiv").addEventListener("keydown", function (e){ if (e.keyCode == 8) { this.innerHTML += "&#10240;".repeat(4); e.preventDefault(); } //moves cursor } ...

The process of integrating markdown markdown syntax into a React component using MDX

What is the most effective method to incorporate content from a markdown file foo.md into a component <Bar />? Will props need to be used for this? Can MDX handle such scenarios effectively? Your help is greatly appreciated! ...

react: implement custom context menu on videojs

Can someone assist me with adding a quality selector and disabling the right-click option in a webpage that uses videojs? I am unsure about using plugins, as there were no examples provided in react. Any guidance would be appreciated. VideoPlayer.js impor ...