Last active
February 8, 2024 22:38
-
-
Save hnykda/835b0daff2410a92f14e6a14bb84a535 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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