Next.js Discord

Discord Forum

Read and Write to json

Answered
Arinji posted this in #help-forum
Open in Discord
Before i start, im local hosting this so dont worry about vercel not allowing to write json

import Hero from "./hero";

import { getMetadata } from "@/app/meta";

import { promises as fs } from "fs";
import { getJson } from "@/data/getJson";
import { unstable_cache } from "next/cache";

export type JsonData = {
  sign: number;
  trash: number;
  hoglan: number;
  gui: number;
};
export default async function Page() {
  const data = (await unstable_cache(
    async () => {
      const file = await fs.readFile(
        process.cwd() + `/data/${"contentDownloads"}.json`,
        "utf8"
      );
      const locContent = JSON.parse(file);
      return locContent;
    },
    ["json"],
    {
      tags: ["content"],
      revalidate: 1,
    }
  )()) as JsonData;

  return (
   
        <Content serverData={data} />
     
  );
}
this is my page at /content,

my json file
{"sign":58,"trash":51,"hoglan":50,"gui":50}

my button
"use client";


import { WriteNewJson } from "./writeJson";
import { useRouter } from "next/navigation";

export default function DownloadButton({
  fileName,
  downloadName,
}: {
  fileName: string;
  downloadName: string;
}) {
  const router = useRouter();
  return (
    <button
      onClick={async () => {
        await WriteNewJson({
          downloadName,
        });
        router.refresh();
        router.push(`/`);
      }}
     
    >
            <p c>DOWNLOAD</p>
    </button>
  );
}

my action
"use server";
import { getJson } from "@/data/getJson";
import { setJson } from "@/data/setJson";
import { revalidatePath, revalidateTag } from "next/cache";

export async function WriteNewJson({ downloadName }: { downloadName: string }) {
  const prevJson = await getJson("contentDownloads");
  prevJson[downloadName] += 1;
  const newJson = JSON.stringify(prevJson);
  await setJson("contentDownloads", newJson);
  revalidatePath("/content");
}

Why is the page not updating to show the new data from the json
Answered by Arinji
ok router.push was the issue
View full answer

1 Reply

ok router.push was the issue
Answer