So yeah.... i've had a problem with dispatching redux thunk actions within Next.
and... it would make sense for it be done the Next kinda way.
As Followed:
async function getData() {
const res = await fetch('https://api.example.com/...')
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Page() {
const data = await getData()
return <main></main>
}
I made a package that will allow you to dispatch thunk actions within the Next getData
callback.
Declare some thunk actions
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
export const fetchContent = createAsyncThunk(
"content/fetchContent",
async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/photos");
const data = await res.json();
return data;
},
);
import createReduxFetch
, add thunkActions
as a second argument, pass your callbacks in that object.
import { fetchContent } from "./thunkActions";
import { createReduxFetch } from "next-redux-fetch";
export const store = createReduxFetch(
{ reducer: {} }, // add whatever redux logic.
{
thunkActions: { fetchContent },
},
);
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;
Call as the following:
note: bootstrap.tsx is just a client wrapper.
"use client";
import dynamic from "next/dynamic";
import React from "react";
const Demo = dynamic(() => import("../../components/demo"), {
ssr: false,
});
export default function Bootstrap({ data }: { data: Record<string, any> }) {
return <Demo data={data} />;
}
Then the following:
import { store } from "../../../redux/store/store";
import Bootstrap from "./bootstrap";
async function getData() {
const res = await store.dispatch(store.thunkActions.fetchContent());
return res;
}
export default async function Page() {
const data = await getData();
return <Bootstrap data={data} />;
}
Voila ...
I'm curious to get some feedback. What would be useful to add , or improve. Roast it :)
I know i could handle error handling a bit better.
Package
https://www.npmjs.com/package/next-redux-fetch
Github
Top comments (0)