What steps can I take to ensure that when the user clicks the logout button, they are redirected to the home component?

Struggling to find a way to direct the user back to the Home component after logging out. The API functionality has been tested and is working properly.

I'm unsure how to properly implement the logout method in the current context to allow for successful logout and redirection to the Home component.

Currently, when clicking on Logout, the Grid component goes blank instead of redirecting to the Home component. How can this issue be resolved?

Below is the code snippet for App.js:

const App = () => {
return (
    <>
        <Router>
            <Switch>
                <Route exact path="/" component={Home} />
                <ProtectedRoute path="/gallery" component={Grid} />
            </Switch>
        </Router>
    </>
   );
}

And here is the section from Navbar.js file:

import { Link as RouterLink } from "react-router-dom";
import { useHistory } from "react-router-dom";

const settings = ['Profile', 'Account', 'Gallery', 'Logout'];
let authToken  = localStorage.getItem('token');



const settingsSelection = (settings) => {
    switch (settings) {
        case "Logout":
            return "/";
    }
};

const logout = () => {
        const headers = {
            "Accept": 'application/json',
            "Authorization": `Bearer ${authToken}`
        };

        const data = "";

        axios.post('http://127.0.0.1:8000/api/logout', data, {headers})
            .then(resp => {
                localStorage.removeItem('token');
                history.push('/');
            }).catch(err => {
            console.log(err);
        });
}


{settings.map((setting) => (
        <MenuItem key={setting} onClick={handleCloseUserMenu}>
            <Typography
                textAlign="center"
                component={RouterLink}
                to={settingsSelection(setting)}
                // onClick={logout()}
            >
                {setting}
            </Typography>
        </MenuItem>
))}

Answer №1

Recommend using useNavigate rather than useHistory.

import { useNavigate } from "react-router-dom";
const navigate = useNavigate();

const logout = () => {
        const headers = {
            "Accept": 'application/json',
            "Authorization": `Bearer ${authToken}`
        };

        const data = "";

        axios.post('http://127.0.0.1:8000/api/logout', data, {headers})
            .then(resp => {
                localStorage.removeItem('token');
                navigate("/");
            }).catch(err => {
            console.log(err);
        });
}


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

Troubleshooting: React App Modules Not Downloading

Recently, I created a homepage containing multiple links and followed a tutorial on how to link to another page within the website. As instructed, one of the initial steps was to install a dependency using the following command: sudo npm install --save r ...

Encountering a Django Channels issue while loading the JavaScript wrapper

After successfully running the server, the following appeared in my cmd prompt: System check identified no issues (0 silenced). January 21, 2020 - 17:43:42 Django version 3.0.2, using settings 'crm.settings' Starting ASGI/Channels version 2.4.0 ...

Utilizing vue-router to create two separate navigation bars where only one link is highlighted as active

In my setup, I have implemented two sections with navigation structured as follows: <ul class="navigation-list"> <li v-for="(route, index) in navRoutes"> <router-link :to="route.path"> <span>{{ route.name }}</span> ...

Understanding the attribute types in Typescript React

While working on code using Typescript + React, I encountered an error. Whenever I try to set type/value in the attribute of <a> tag, I receive a compile error. <a value='Hello' type='button'>Search</a> This piece o ...

Using JavaScript regex to eliminate content enclosed in parentheses, brackets, and Cyrillic characters

Is there a way to transform (Test 1 / Test 2) [Test 3] Отдел / Here is title - subtitle (by Author) - 1234 (5678-9999), descriptions (best), more descriptions into Here is title - subtitle (1234) (descriptions) using a combination of JavaScript an ...

Tips for showing form values in pop-up boxes based on their unique identifiers

I am experiencing an issue with displaying posted values in a pop-up box. Specifically, when I click on "Book now", it only shows one set of id values for all entries. For example, if I click on the 1st row's "Book now" button, it displays the values ...

Difficulty with Horizontal Mousewheel Scrolling

Struggling to implement a horizontal scrolling feature (via mousewheel) for both containers in the code below. I want this feature to be easily applied to any future container creations as well. <body> <style> #container { display: flex ...

Is it possible to use React to redirect a page and display data changes?

I am not a React user but have a question about refreshing an HTML table after record operations like UPDATE, DELETE, or CREATE. Imagine a table structure like this: [New Record] John <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

How do I leverage one of my props in React to iterate through my JSON data?

My goal is to utilize props.type to modify the mapping of the JSON in the H5 section. I attempted to accomplish this similar to how I did with the className, but unfortunately, I haven't been able to find the correct method. import text from "../ ...

Using Javascript, the sum of inputs is calculated based on the keyup event

I am a beginner in javascript and I'm learning about events. Below is the HTML code for a table that displays income titles and their respective prices. <table class="table table-hover table-bordered" id="incomeId"> <thead> <tr&g ...

Unable to get create-react-library to function properly with styled components

Using create-react-library to develop my component library has been a smooth process overall. However, when attempting to integrate Styled Components, I encountered an unexpected React hooks error. If you're interested, take a look at the code here: ...

Having trouble retrieving accurate JSON data from an excel workbook

Currently, I am utilizing the npm module xlsx for the purpose of writing and reading JSON data. My goal is to take this JSON data and write it into an Excel file: { "name": "John", "class": 1, "address" : [ { "street": "12th Cross", "city": "London" }, { ...

Modifying the color of drawings on a Javascript canvas

I am currently working on developing a drawing board using HTML and JavaScript (Node.js on the server side). One challenge I'm facing is implementing a color picker that allows users to change the paint color dynamically. While I could hard code the c ...

Issue with NodeJS SQL Login: Received error (ERR_HTTP_HEADERS_SENT): Headers cannot be set after being sent to the client

Hi there, I am fairly new to working with nodeJS and I have encountered an issue that I suspect lies within the second if statement inside "db.query..." in the code provided below. An error message showing ERR_HTTP_HEADERS_SENT]: Cannot set headers after ...

The expanding submenus within each menu are activated by a simple click

I am facing an issue with my menus and submenus. Whenever I click on a menu, all the associated submenus also open up. How can I make it so only the parent submenu opens? https://i.stack.imgur.com/7FDq3.png const [subMenu, setSubMenu] = useState(false) ...

Sharing a Redux action with nested child components

The current structure I am working with looks like this: UserPage -> Container |-----UserList -> Dumb Component |--- User ->Dumb Component My action and dispatch are connected to the container, which is UserPage. function mapStateToProps(state) ...

Leveraging Deferred in conjunction with AJAX

I am facing an issue with a series of JavaScript functions that make database calls using AJAX. I need these functions to finish executing and update variables before moving on to the final function. I have attempted to use jQuery $.when but it is not work ...

An issue occurred while recognizing the create-react-app, despite being duly installed

After successfully installing create-react-app, I encountered an issue when attempting to create my own app. A message stating 'create-react-app' is not recognized as an internal or external command appeared. You can see the exact error message ...

"Learn how to transfer a selected value from a parent ASP.NET dropdownlist to a textbox in a popup window using JavaScript

I'm struggling to pass the value from a dropdown list in the parent ASPX form to a textbox in the child ASPX form. Parent JavaScript: The first script is used to open the popup window <script type="text/javascript"> var popup; ...

Utilizing nested grouping in mongoose schemas

I am facing a challenge while attempting to execute a nested group query in MongoDB. Is there a way to group data by both date and campaign ID, ensuring that each campaign ID contains a nested array of creatives with their respective data (views and clicks ...