Skip to content

Instantly share code, notes, and snippets.

@hnykda
Last active February 8, 2024 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnykda/835b0daff2410a92f14e6a14bb84a535 to your computer and use it in GitHub Desktop.
Save hnykda/835b0daff2410a92f14e6a14bb84a535 to your computer and use it in GitHub Desktop.
"use client";
import React, { useState, useEffect } from "react";
const Comp = ({
existingDataPromise,
moveItemSideEffect,
}: {
existingDataPromise: Promise<string[]>;
moveItemSideEffect: () => void;
}) => {
const [dataList, setDataList] = useState<string[]>([]);
useEffect(() => {
existingDataPromise.then((data) => {
setDataList(data);
});
}, [existingDataPromise]);
const moveItem = (index: number, direction: "up" | "down") => {
setDataList((prevList) => {
const newList = [...prevList];
const element = newList.splice(index, 1)[0];
const newIndex = direction === "up" ? index - 1 : index + 1;
newList.splice(newIndex, 0, element);
return newList;
});
moveItemSideEffect();
};
return (
<div className="flex flex-col">
{dataList.map((item, index) => (
<div key={index} className="flex flex-row gap-2">
{item}
<button
onClick={() => moveItem(index, "up")}
disabled={index === 0}
className="bg-red-500"
>
Up
</button>
<button
onClick={() => moveItem(index, "down")}
disabled={index === dataList.length - 1}
className="bg-green-500"
>
Down
</button>
</div>
))}
</div>
);
};
export default Comp;
import Comp from "./Comp";
import { revalidatePath } from "next/cache";
export default function Home() {
const getData = async () => {
const resp = await fetch("https://api.sampleapis.com/wines/reds");
const json = await resp.json();
return json
.map((item: { wine: string }) => item.wine)
.slice(0, 5)
.sort((a: string, b: string) => a.length - b.length);
};
const moveItemSideEffect = async () => {
"use server";
revalidatePath("/");
};
return (
<main>
<Comp
existingDataPromise={getData()}
moveItemSideEffect={moveItemSideEffect}
/>
</main>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment