Next.js Discord

Discord Forum

Updating a rows column after updating row data

Answered
Prairie yellowjacket posted this in #help-forum
Open in Discord
Prairie yellowjacketOP
So, I'm just redirecting to the current page to refresh the row data right now and I know this is the shitty way of doing it.

I haven't been in frontend development in years and this is my first time with react/next so I apologize for handling this incorrectly.

Basically, I have a table that displays 10 rows at a time. Each row has an 'actions' menu. From that menu, I can change the status of a row, let's say, toggle between green enabled and red disabled.

I wouldn't use useState in this instance, correct? Because it would have to be dynamic for each record in a table?

I just want to update this in real time, no page refresh.

I am currently using the datatables from shadcn-ui, so this would be managed from the 'columns.tsx' file. I'm not looking for any handouts, I'm just looking for help in what to search on the web to find examples of this or get some feedback here.
Answered by Chum salmon
You would use useState if you want the update to be instance because state changes cuases re-render. At lest it's one way to do it easily.

Let's say you have state of the status and array of rows as follows:
const [rows, setRows] = useState<RowType[]>([]);
const [enabled, setEnabled] = useState(false);

Then you may have the ui like this:
<span 
   onClick={() => toggleEnable(row.id)
   className="{`${enabled : "text-green-500" : "text-red-500"}`}
>{enable ? "enabled" : "disabled"}</span>

And the toggle function might look something like:
const toggleEnable = (id: number) => {
   setRows(prev => {
      return prev.map((row) => (row.id === id ? {...row, status: !row.status} : row))
   })
}
View full answer

3 Replies

Chum salmon
You would use useState if you want the update to be instance because state changes cuases re-render. At lest it's one way to do it easily.

Let's say you have state of the status and array of rows as follows:
const [rows, setRows] = useState<RowType[]>([]);
const [enabled, setEnabled] = useState(false);

Then you may have the ui like this:
<span 
   onClick={() => toggleEnable(row.id)
   className="{`${enabled : "text-green-500" : "text-red-500"}`}
>{enable ? "enabled" : "disabled"}</span>

And the toggle function might look something like:
const toggleEnable = (id: number) => {
   setRows(prev => {
      return prev.map((row) => (row.id === id ? {...row, status: !row.status} : row))
   })
}
Answer
Prairie yellowjacketOP
Perfect, JKT. Above and beyond.