Home > Software engineering >  My useNavigate doesn't work inside onClick function (react-router-dom) (localstorage)
My useNavigate doesn't work inside onClick function (react-router-dom) (localstorage)

Time:01-26

By default I receive in my localStorage an array " name" with an item at position [0]. In my handleExitChat function, I delete this item that I receive in my localStorage and direct the user to the main page '/' through the navigate that receives useNavigate(). When I submit the "name" item from my localStorage is deleted as I wanted, but I am not directed to the main page '/', I can only be directed to the main page when I put it in the url and not through of the button. I would like to know why navigate is being prevented in this function.

import * as C from './styles';

import { useNavigate } from 'react-router-dom';

const Chat = () => {
  const navigate = useNavigate();

  const handleExitChat = async () => {
    const remove = await JSON.parse(localStorage.removeItem("name"))[0];
    navigate('/');
  }

  return (
    <C.Container>
       <C.RemoveChat>
         <button onClick={handleExitChat}>Logout</button>
       </C.RemoveChat>
    </C.Container>
  )
}

export default Chat;

erro

SyntaxError: "undefined" is not valid JSON
    at JSON.parse (<anonymous>)
    at handleExitChat (index.jsx:50:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
    at executeDispatch (react-dom.development.js:9041:1)
    at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
    at processDispatchQueue (react-dom.development.js:9086:1)
    at dispatchEventsForPlugins (react-dom.development.js:9097:1)

CodePudding user response:

Issues

From what I can see there are a few issues specifically in this handleExitChat click handler.

  1. localStorage.removeItem is a void return. See return value.
  2. An error is thrown when attempting to JSON parse the undefined return value from removing the item. undefined isn't valid JSON. There's just simply nothing to parse.

The error is thrown and code execution is halted. The navigate("/") line is never reached.

Solution

Just remove the item from storage and issue the navigation action. localStorage is synchronous, so there is nothing to await for.

const handleExitChat = () => {
  localStorage.removeItem("name"));
  navigate('/');
};

And just in case this Chat component is ever rendered inside any form element you'll want to specify that the button is not a submit button. button elements are type="submit" by default if not specified.

<button type="button" onClick={handleExitChat}>
  Logout
</button>
  • Related