Next.js Discord

Discord Forum

How to manage state in my React application?

Unanswered
Southern African anchovy posted this in #help-forum
Open in Discord
Southern African anchovyOP
How to manage state in my React application?

I'm building a resume builder using NextJs, TailwindCSS, TypeScript, Prisma and PostgreSQL.

I have a Resume model, that is associated to many WorkEntries, and each WorkEntry is associated to the resume it belongs.
Both the Resume and the WorkEntry maps to tables in the database.

I have page that looks like so:

export default function Page() {
  const [resume, setResume] = useState(null)

  // ... useEffect to fetch the resume from the database

  return (
    <div>
      <h1>{resume.title}</h1>
      <section><WorkEntries resume={resume} /></section>
    </div>
  )
}

function WorkEntries({resume}) {
  const [workEntries, setWorkEntries] = useState(resume.workEntries)

  return (
    <div>
      {workEntries.map((workEntry) => (<WorkEntry entry={workEntry} />))}
    </div>
  )
}

function WorkEntry({entry}) {
  const [workEntry, setWorkEntry] = useState(entry)

  return (
    <div>
      <div>{workEntry.jobPosition}</div>
      <div>{workEntry.jobPosition}</div>
      ...
    </div>
  )
}


The problem is that whenever I perform an action in the WorkEntry component that changes
the record in the database and the workEntry state variable, the UI state becomes out of sync with the database state ...

This is because here I get the WorkEntrys state from the caller (WorkEntries):
  const [workEntry, setWorkEntry] = useState(entry)


Which means that I also have to update the resume state ....

So my question is how would you manage state in this case?

Should the WorkEntries component fetch the workEntries directly from the database using the resumeId instead of via its prop??

What if my resume has other records, such as EducationEntries, Projects, etc. should all of them be fetched directly from the database and not derived from the resume?

0 Replies