Implement global state management for movies; refactor RootLayout to fetch movies and wrap children in GlobalStoreProvider; enhance database schema with additional movie fields and CRUD operations.

This commit is contained in:
Norbert Maciaszek
2025-08-05 21:51:32 +02:00
parent 922e55f27f
commit 08d766bf8c
4 changed files with 77 additions and 9 deletions

View File

@@ -2,6 +2,8 @@ import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { Navbar } from "@/components/organisms/Navbar";
import { GlobalStoreProvider } from "./store/globalStore";
import { getMovies } from "@/lib/db";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -18,19 +20,23 @@ export const metadata: Metadata = {
description: "Generated by create next app",
};
export default function RootLayout({
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const movies = await getMovies();
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<Navbar />
<GlobalStoreProvider initialMovies={movies}>
<Navbar />
{children}
{children}
</GlobalStoreProvider>
</body>
</html>
);

View File

@@ -0,0 +1,44 @@
"use client";
import { movies } from "@/lib/db/schema";
import { createContext, FC, use, useState } from "react";
type GlobalStore = {
movies: (typeof movies.$inferSelect)[];
addMovie: (movie: typeof movies.$inferSelect) => void;
deleteMovie: (id: number) => void;
};
const globalStore = createContext<GlobalStore>({
movies: [],
addMovie: () => {},
deleteMovie: () => {},
});
type Props = {
children: React.ReactNode;
initialMovies: GlobalStore["movies"];
};
export const GlobalStoreProvider: FC<Props> = ({ children, initialMovies }) => {
const [movies, setMovies] = useState<GlobalStore["movies"]>(initialMovies);
const addMovie = async (movie: GlobalStore["movies"][number]) => {
if (movies.find((m) => m.id === movie.id)) return;
setMovies((prev) => [...prev, movie]);
};
const deleteMovie = async (id: number) => {
setMovies((prev) => prev.filter((m) => m.id !== id));
};
return (
<globalStore.Provider value={{ movies, addMovie, deleteMovie }}>
{children}
</globalStore.Provider>
);
};
export const useGlobalStore = () => {
return use(globalStore);
};