DEV Community

EliHood
EliHood

Posted on • Updated on

Roast my Next npm package....

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>
}
Enter fullscreen mode Exit fullscreen mode

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;
  },
);

Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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} />;
}
Enter fullscreen mode Exit fullscreen mode

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} />;
}
Enter fullscreen mode Exit fullscreen mode

Voila ...

Image description

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

https://github.com/EliHood/next-redux-fetch

Top comments (0)