Refreshing the list in a Next.js to-do application post-deletion: a step-by-step guide

I am currently developing a basic to-do application using Next.js, TypeScript, and Axios. I have successfully implemented the delete functionality for tasks, but I am facing an issue with refreshing the tasks list after deletion. I would appreciate any suggestions or guidance on how to achieve this. Thank you!

// pages/index.tsx

import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";

// More code here...

// modules/hooks/useFetchTasks.ts

import { useState, useEffect, useCallback } from "react";

// More code here...

export const useFetchTasks = () => {
  const [tasks, setTasks] = useState<TasksResponse | null>(null);

  // More code here...

};

Answer №1

To update your list after making an API call, you can pass the setTasks function from your useFetchTasks hook to your button.

const OperationButtons: React.VFC<OperationButtonProps> = (props) => {
    const handleDelete = async () => {
        try {
            await deleteTask(props.taskId);
            props.setTasks(prevTasks => prevTasks.tasks.filter(task => task.id !== props.taskId))
        } catch (e) {
            console.log(e);
        }
    };

    return (
        <Stack direction="row">
            <IconButton aria-label="edit">
                <EditIcon />
            </IconButton>
            <IconButton edge="end" aria-label="delete" onClick={handleDelete}>
                <DeleteIcon />
            </IconButton>
        </Stack>
    );
};

const IndexPage = () => {
    const { tasks, setTasks } = useFetchTasks();

    return (
        <>
            <Typography variant="h3" align="center" marginTop={3}>
                TODO LIST
            </Typography>
            {tasks && (
                <Container maxWidth="sm">
                    <List sx={{ width: '100%' }}>
                        {tasks.tasks.map((task) => (
                            <ListItem
                                key={task.id}
                                secondaryAction={<OperationButtons taskId={task.id} setTasks={setTasks} />}
                            >
                                <ListItemAvatar>
                                    <Avatar>
                                        <FactCheckIcon />
                                    </Avatar>
                                </ListItemAvatar>
                                <ListItemText
                                    primary={task.description}
                                    secondary={task.created_at}
                                />
                            </ListItem>
                        ))}
                    </List>
                </Container>
            )}
        </>
    );
};

export const useFetchTasks = () => {
    const [tasks, setTasks] = (useState < TasksResponse) | (null > null);

    const fetchTasks = useCallback(async () => {
        try {
            const { data } = await getTasks();
            setTasks(data);
        } catch (e) {
            console.log(e);
        }
    }, []);

    useEffect(() => {
        fetchTasks();
    }, []);

    return {
        tasks,
        fetchTasks,
        setTasks
    };
};

export default IndexPage;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using NextJS <Link, mobile users may need to tap twice to navigate

Whenever I use the NextJS <Link tag on my mobile device, I notice that I have to double-tap for the link to actually route to the desired page. Take a look at the code snippet below: <Link href="/methodology" passHref={true} ...

Issue with DTO and a custom decorator in NestJS

I am currently facing an issue with using a DTO alongside a custom decorator within a NestJS controller for body validation. I am sending a request using multipart/form data, which requires me to parse the data from a string to JSON. However, when attempti ...

Importing images in Typescript is a simple and effective

I came across a helpful solution at this Stackoverflow thread However, I encountered an error: [ts] Types of property 'src' are incompatible. Type 'typeof import("*.png")' is not assignable to type 'string | undefined& ...

Confirm that the attributes of a JSON object align with an Enum

Having a Lambda function that receives a JSON object from the Frontend over HTTPS, I need to perform validation on this object The expected structure of the body should be as follows (Notifications): interface Notifications { type: NotificationType; f ...

Steps for appending a string to a variable

Currently working on creating a price configurator for a new lighting system within homes using Angular 7. Instead of using TypeScript and sass, I'm coding it in plain JavaScript. Page 1: The user will choose between a new building or an existing one ...

Issues with NextJS detecting environmental variables

I recently encountered an issue with my NextJS app running on Next.js v12.2.5 where it appears to be ignoring the environment variables I've configured. To address this, I created a .env.local file with the following content: NEXT_PUBLIC_SERVER_URL=h ...

The issue persists in Angular 5 and asp.net MVC where the ID number continues to increase despite being deleted

Currently, I am using Angular 5 (VS CODE) for the front-end and asp.net mvc/entity framework (VS2017) for the back-end. My CRUD methods are functioning properly; however, I have encountered an issue where the ID of a newly created row keeps increasing even ...

What is the best way to incorporate an interface in TypeScript that is both callable and has properties?

Given the scenario where an interface is defined as: interface FooWithBar { ():void; bar():void; } I am struggling with writing the implementation. I attempted the following: function foo(){ } foo.bar = function(){ }; This approach did not wo ...

Retrieve input value in Angular 8 using only the element's ID

Can the value of an input be obtained in Angular 8 with TypeScript if only the element's id is known? ...

Discovering the data types for node.js imports

When starting a node.js project with express, the code typically begins like this - import express = require('express') const app = express() If I want to pass the variable 'app' as a parameter in typescript, what would be the appropri ...

Youtube video embedding showing cut edges on smaller screens

Looking for assistance with a Next.js and tailwind site I am building. Having trouble getting the video component to display properly on mobile screens. Tried various fixes but the video still gets cut off on smaller screen sizes. If anyone has a soluti ...

Can anyone provide guidance on how to trigger an HTTP 500 error in my React.js and Next.js applications?

To ensure that our custom error page is displayed instead of the default HTTP 500 error following a recent security vulnerability, I am looking to purposely simulate the error. While we have special processing in place for 404 and 403 errors on our site, ...

What is the correct way to apply type in the .call() method?

I need help finding a solution for the following issue interface IName { name:string; } let obj1:IName = { name: "LINUS" } function profileInfo (age:number,location:string):string{ return `${this.name} is ${age} years old and is from ${location ...

Utilizing JSON API filtering within a Next.js application

Recently delving into the world of coding, I've embarked on a personal project that has presented me with a bit of a challenge regarding API filtering. My goal is to render data only if it contains a specific word, like "known_for_department==Directin ...

Identifying Gmail line breaks in the clipboard using Angular

I'm currently working on a feature that allows users to paste content from Gmail into a field and detect line breaks. The field doesn't have to be a text area, I just need to identify the line breaks. However, there seems to be an issue with det ...

How can I find the "types" specific to modules within the "firebase" library?

I have a question that applies to various scenarios, with Firebase serving as an example. When working on my react project, I find myself wanting to import firebase from "@firebase/app", which is logical. However, if I want the const locationRef ...

Dealing with an empty array in a Next.js React application

While working with React, I encountered an error message stating "error: type is not supported." It seems like this error occurs when one of the array items is empty and the script cannot read that value. Specifically, if blog.author is empty, the syntax u ...

Error: The object 'exports' is not defined in geotiff.js at line 3

Looking to integrate the geotiff library with Angular 6.1.0 and TypeScript 2.9.2. Installed it using npm i geotiff Encountering the following error in the browser console: Uncaught ReferenceError: exports is not defined at geotiff.js:3 After r ...

What is the best way to create additional layouts for subdirectories in NextJS?

I have the main template that wraps my entire application: function MyApp({ Component, pageProps }: AppProps) { return ( <> <Template> <Component {...pageProps} /> </Template> </> ); } I am loo ...

The next.js Incremental Static Regeneration feature can optimize response times to as fast as

We have hit a wall in terms of build times in our CI/CD process. With 9k pre-rendered pages and the switch to ISR, we are now able to update and generate the less relevant pages on-the-fly. During a small load test, we noticed a significant drop in the ov ...