9 Synchronized State

Synchronized State

Check this guide (opens in a new tab) to learn more about synchronizing with effects.

  1. Reuse the application from 7 Server Actions.

  2. Create a API to create, retrieve, and delete records using the data repository:

    app/api/records/route.js
    import * as records from "@/repos/records";
     
    export async function GET(request) {
      return Response.json(await records.read());
    }
     
    export async function POST(request) {
      const data = await request.json();
      return Response.json(await records.write({ title: data.title }));
    }
  3. Update your page to use API calls to create, retrieve, and delete records:

    • Use an effect to load the records into a state variable.
    • Use a state variable to keep track of when to reload the records.
    app/page.jsx
    "use client";
     
    import { useState, useEffect } from "react";
    import Record from "@/components/record";
     
    export default function Home() {
      const [records, setRecords] = useState([]);
      const [stale, setStale] = useState(true);
     
      useEffect(() => {
        if (stale) {
          fetch("/api/records")
            .then((response) => response.json())
            .then((data) => setRecords(data));
          setStale(false);
        }
      }, [stale]);
     
      return (
        <div>
          {records.map((record) => (
            <Record key={record.id} record={record} />
          ))}
        </div>
      );
    }