Is there a way to ensure that the useEffect hook only runs after the useNavigate hook has been utilized? How can I prompt the initial render to occur only following the useNavigate

After using the useNavigate hook, how can I ensure that useEffect runs and triggers an initial render in my component?

Within the App.js component, which serves as the homepage with the "/" path, the following code is implemented:

const [contacts, setContacts] = useState([]);
     
useEffect(() => {
        const retrieveContacts = async function () {
          const response = await api.get("/");
          setContacts(response.data);
        };
        retrieveContacts();
      }, []);

In the Delete.js component, located at the "/delete" path, the following code is used:

  async function deleteContact() {
     await props.deleteContactHandler(contact._id);
     navigate("/");
  }

Initially, two contacts are retrieved from the database within the App.js component resulting in the displayed screen shown below:

https://i.stack.imgur.com/UzUaS.png

Subsequently, when attempting to delete one of the contacts (Mike), and returning to the homepage upon confirmation, both contacts still appear on the screen.

This inconsistency occurs due to the failure of the useEffect function to execute after navigating back to the App.js component, thus not updating the list of contacts.

To address this issue, forcing an initial render of the App.js component after the useNavigate hook is triggered by invoking:

navigate("/").

is necessary. This action ensures that all components are refreshed, showing the most recent state without any remnants of previously deleted data.

Answer №1

It appears that the navigation function is directing the app to the / URL, and since this URL remains the same as before, the home component is not being unmounted. Instead, the previously mounted component is still in use. When you refresh the app by pressing F5, the entire app is rendered again, causing the home component to be re-rendered.

If you want to force the component to re-render when you click the delete button, you can do something like this:

const [updated, setUpdated] = useState(false);
 
useEffect(() => {
        const retrieveContacts = async function () {
          const response = await api.get("/");
          setContacts(response.data);
        };
        retrieveContacts();
      }, [updated]);

Then, pass the setter down to the delete component like this:

async function deleteContact() {
     await props.deleteContactHandler(contact._id);
     setUpdated(true);
     navigate("/");
  }

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

Exploring the world of React-Bootstrap elements and properties

I'm currently diving into a Bootstrap home project and it's my first time working with Bootstrap. I came across a tag that has an 'inverse' attribute among others like 'fixedTop', 'fluid', and 'collapseOnSelect& ...

What is the best way to assign a unique background color to each individual card in my card list?

I have a list of cards and I want to assign a unique color to each card in the list. I attempted to do this on my own, but it ended up being more complex than I anticipated. Here is the list of cards: return ( <Container> <Row className=&qu ...

What is the process for updating a particular index in a list?

Currently, I am delving into React by working on a task master app. The concept is simple - each user input becomes a new task in an array of tasks. The app features Add, Delete, and Update buttons for managing these tasks. Everything is functioning smoot ...

I am struggling to apply custom CSS styles to the scrollbar within a Card component using MUI react

import React from "react"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/Ca ...

Creating a dynamic state management system for multiple Collapse components can be achieved by utilizing

I am trying to create a Collapse menu from array data, Currently, when I click on any menu all sub menus expand I believe my issue lies in not being able to set a unique "open" state for each Main menu I want to avoid assigning a "state" to accommodate ...

How to successfully load the google-map-react library

After installing the google-map-react library locally in my app, I verified that it is listed in my package.json under dependencies. The corresponding folder also exists in the node_modules directory. However, when attempting to reference the component con ...

Developing a transparent "cutout" within a colored container using CSS in React Native (Layout design for a QR code scanner)

I'm currently utilizing react-native-camera for QR scanning, which is functioning properly. However, I want to implement a white screen with opacity above the camera, with a blank square in the middle to indicate where the user should scan the QR code ...

Implementing automatic value setting for Material UI slider - a complete guide

I am working on developing a slider that can automatically update its displayed value at regular intervals. Similar to the playback timeline feature found on platforms like Spotify, Soundcloud, or YouTube. However, I still want the slider to be interactive ...

Removing chips in Material UI can be easily accomplished by following these steps

Recently, I implemented a feature where chips are generated as the user types in a text field and clicks on create. A chip is then displayed with the entered text. Now, I am looking to add the ability to delete these chips dynamically. You can view the s ...

Designing an interactive header interface using React and Material UI

My header.jsx file contains the following code: // Default Import Statements var Login = require(login.jsx) const HeaderComponent = React.createClass({ getInitialState () { return { loggedIn: false, }; }, render() { return ( ...

The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button. Although I managed to get a sorted array displayed in the console log using the h ...

React JS for loop not displaying any output

I am trying to create a component that loops from 0 to the value entered as a prop. if (props.number !== "" && props.toPow !== "") { for (let i = 0; i < props.toPow; i++) { return ( <div> & ...

Placing a new item following each occurrence of 'X' in React components

Currently, I am working with a React component that uses Bootstrap's col col-md-4 styles to render a list of items in three columns. However, I am facing an issue where I need to add a clearfix div after every third element to ensure proper display of ...

Guide to activating the isActive status on a live link within a map iteration utilizing the NEXTUI navigation bar

Check out the new NEXTUI navbar I'm using: I am having trouble setting the isActive property on the active link in my NavBar component in Next.js. I couldn't find much help on Google, so I'm hoping someone here has experience with this or k ...

Using the DatePicker component with non-escaped Latin alphabet characters in date-fns for ReactJS

While attempting to integrate the DatePicker component from Material UI into my React project, I encountered an error. Although many attributed the issue to a version discrepancy, what ultimately resolved the problem for me was assigning a value to the Da ...

"Encountering difficulties while trying to modify the QuillNoSSRWrapper value within a Reactjs

Currently, I am working on a project involving ReactJS and I have opted to use the Next.js framework. As of now, I am focused on implementing the "update module" (blog update) functionality with the editor component called QuillNoSSRWrapper. The issue I ...

Encountering a 304 status error in the HTTP GET response after deploying a React app on Netlify

After deploying my react application on Netlify, I used the npm run build command to create the local scripts and manually deployed them in production mode on Netlify. The build scripts were generated on my local machine and then uploaded to the Net ...

Enhance the Material UI Data Grid by customizing the toolbar's default slots with the option to disable the

https://i.stack.imgur.com/0YV9m.png Background In my current project, I am utilizing the Datagrid component from MUI [email protected]. I have disabled the column menu to display the toolbar at the top of the table instead of on individual columns. ...

Auto Suggest: How can I display all the attributes from a JSON object in the options list using material-ui (@mui) and emphasize the corresponding text in the selected option?

Currently, I am facing a requirement where I need to display both the name and email address in the options list. However, at the moment, I am only able to render one parameter. How can I modify my code to render all the options with both name and email? ...

The value entered for creating a payment method is invalid: the card must be in the form of an object

I am in the process of setting up a payment method using the Next.js library from Stripe. Here is the code snippet: import React, { FunctionComponent } from 'react'; import type { DisplaySettingsProps } from '@company/frontoffice/types' ...