kandi background
Explore Kits

EventBus | Event bus for Android and Java that simplifies communication | Pub Sub library

 by   greenrobot Java Version: V3.3.1 License: Apache-2.0

 by   greenrobot Java Version: V3.3.1 License: Apache-2.0

Download this library from

kandi X-RAY | EventBus Summary

EventBus is a Java library typically used in Messaging, Pub Sub applications. EventBus has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has medium support. You can download it from GitHub, Maven.
Prepare subscribers: Declare and annotate your subscribing method, optionally specify a [thread mode](https://greenrobot.org/eventbus/documentation/delivery-threads-threadmode/):. Read the full [getting started guide](https://greenrobot.org/eventbus/documentation/how-to-get-started/). There are also some [examples](https://github.com/greenrobot-team/greenrobot-examples). Note: we highly recommend the [EventBus annotation processor with its subscriber index](https://greenrobot.org/eventbus/documentation/subscriber-index/). This will avoid some reflection related problems seen in the wild.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • EventBus has a medium active ecosystem.
  • It has 23725 star(s) with 4635 fork(s). There are 1093 watchers for this library.
  • There were 2 major release(s) in the last 12 months.
  • There are 103 open issues and 451 have been closed. On average issues are closed in 107 days. There are 41 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of EventBus is V3.3.1
EventBus Support
Best in #Pub Sub
Average in #Pub Sub
EventBus Support
Best in #Pub Sub
Average in #Pub Sub

quality kandi Quality

  • EventBus has 0 bugs and 0 code smells.
EventBus Quality
Best in #Pub Sub
Average in #Pub Sub
EventBus Quality
Best in #Pub Sub
Average in #Pub Sub

securitySecurity

  • EventBus has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • EventBus code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
EventBus Security
Best in #Pub Sub
Average in #Pub Sub
EventBus Security
Best in #Pub Sub
Average in #Pub Sub

license License

  • EventBus is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
EventBus License
Best in #Pub Sub
Average in #Pub Sub
EventBus License
Best in #Pub Sub
Average in #Pub Sub

buildReuse

  • EventBus releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • EventBus saves you 2836 person hours of effort in developing the same functionality from scratch.
  • It has 5811 lines of code, 567 functions and 104 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
EventBus Reuse
Best in #Pub Sub
Average in #Pub Sub
EventBus Reuse
Best in #Pub Sub
Average in #Pub Sub
Top functions reviewed by kandi - BETA

kandi has reviewed EventBus and discovered the below as its top functions. This is intended to give you an instant insight into EventBus implemented functionality, and help decide if they suit your requirements.

  • Checks for subscribers that are visible to the given package .
    • Creates a new subscription .
      • Find methods in single class .
        • Handles a message .
          • Map a throwable to a specific error message id .
            • Executes the given Runnable .
              • Maps a log level .
                • Checks if Android is available
                  • Gets the super subscriber info .
                    • Returns a pending post .

                      Get all kandi verified functions for this library.

                      Get all kandi verified functions for this library.

                      EventBus Key Features

                      Define events: ```java public static class MessageEvent { /* Additional fields if needed */ } ```

                      Prepare subscribers: Declare and annotate your subscribing method, optionally specify a [thread mode](https://greenrobot.org/eventbus/documentation/delivery-threads-threadmode/): ```java @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) {/* Do something */}; ``` Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle: ```java @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { super.onStop(); EventBus.getDefault().unregister(this); } ```

                      Post events: ```java EventBus.getDefault().post(new MessageEvent()); ```

                      EventBus in 3 steps

                      copy iconCopydownload iconDownload
                      ```java
                      public static class MessageEvent { /* Additional fields if needed */ }
                      ```

                      Add EventBus to your project

                      copy iconCopydownload iconDownload
                      implementation("org.greenrobot:eventbus:3.3.1")

                      How can I redirect a user to login when a certain link is clicked using JWT

                      copy iconCopydownload iconDownload
                      import React, { useEffect } from 'react';
                      import { Navigate } from 'react-router-dom';
                      import { useSelector } from 'react-redux';
                      
                      function Uploads() {
                        const { user: currentUser } = useSelector((state) => state.auth);
                      
                        if (!currentUser) {
                          return <Navigate to='/login' replace />;
                        }
                        return (
                          <>
                            <h1 className='page'>UPLOADS</h1>
                          </>
                        );
                      }
                      
                      export default Uploads;
                      
                      import { Navigate, Outlet } from 'react-router-dom';
                      import { useSelector } from 'react-redux';
                      
                      const PrivateRoutes = () => {
                        const { user: currentUser } = useSelector((state) => state.auth);
                        return currentUser 
                          ? <Outlet />
                          : <Navigate to="/login" replace />;
                      }
                      
                      <Routes>
                        <Route path='/' element={<Home />} />
                        <Route element={<PrivateRoutes />}>
                          <Route path='/create/upload' element={<Uploads />} />
                          ... any other protected routes ...
                        </Route>
                        ... other unprotected routes ...
                      </Routes>
                      
                      import React, { useEffect } from 'react';
                      import { Navigate } from 'react-router-dom';
                      import { useSelector } from 'react-redux';
                      
                      function Uploads() {
                        const { user: currentUser } = useSelector((state) => state.auth);
                      
                        if (!currentUser) {
                          return <Navigate to='/login' replace />;
                        }
                        return (
                          <>
                            <h1 className='page'>UPLOADS</h1>
                          </>
                        );
                      }
                      
                      export default Uploads;
                      
                      import { Navigate, Outlet } from 'react-router-dom';
                      import { useSelector } from 'react-redux';
                      
                      const PrivateRoutes = () => {
                        const { user: currentUser } = useSelector((state) => state.auth);
                        return currentUser 
                          ? <Outlet />
                          : <Navigate to="/login" replace />;
                      }
                      
                      <Routes>
                        <Route path='/' element={<Home />} />
                        <Route element={<PrivateRoutes />}>
                          <Route path='/create/upload' element={<Uploads />} />
                          ... any other protected routes ...
                        </Route>
                        ... other unprotected routes ...
                      </Routes>
                      
                      import React, { useEffect } from 'react';
                      import { Navigate } from 'react-router-dom';
                      import { useSelector } from 'react-redux';
                      
                      function Uploads() {
                        const { user: currentUser } = useSelector((state) => state.auth);
                      
                        if (!currentUser) {
                          return <Navigate to='/login' replace />;
                        }
                        return (
                          <>
                            <h1 className='page'>UPLOADS</h1>
                          </>
                        );
                      }
                      
                      export default Uploads;
                      
                      import { Navigate, Outlet } from 'react-router-dom';
                      import { useSelector } from 'react-redux';
                      
                      const PrivateRoutes = () => {
                        const { user: currentUser } = useSelector((state) => state.auth);
                        return currentUser 
                          ? <Outlet />
                          : <Navigate to="/login" replace />;
                      }
                      
                      <Routes>
                        <Route path='/' element={<Home />} />
                        <Route element={<PrivateRoutes />}>
                          <Route path='/create/upload' element={<Uploads />} />
                          ... any other protected routes ...
                        </Route>
                        ... other unprotected routes ...
                      </Routes>
                      

                      How do I implement a Logout functionality from a React Router Link to imports an array?

                      copy iconCopydownload iconDownload
                      const Logout = () => {
                        const dispatch = useDispatch();
                        const navigate = useNavigate();
                      
                        useEffect(() => {
                          dispatch(logout())
                            .then(() => {
                              navigate("/", { replace: true });
                            });
                      
                        }, []);
                      
                        return <LoadingSpinner />;
                      };
                      
                      ...
                      import Login from './components/pages/Login';
                      import Logout from './components/pages/Logout';
                      ...
                      
                      ...
                      
                      <Router>
                        <Navbar />
                        <Routes>
                          <Route path='/' element={<Home />} />
                          <Route path='/my-account' element={<Account />} />
                          <Route path='/login' element={<Login />} />
                          <Route path='/logout' element={<LogOut />} />
                          <Route path='/profile' element={<Profile />} />
                        </Routes>
                        <Footer />
                      </Router>
                      
                      const Logout = () => {
                        const dispatch = useDispatch();
                        const navigate = useNavigate();
                      
                        useEffect(() => {
                          dispatch(logout())
                            .then(() => {
                              navigate("/", { replace: true });
                            });
                      
                        }, []);
                      
                        return <LoadingSpinner />;
                      };
                      
                      ...
                      import Login from './components/pages/Login';
                      import Logout from './components/pages/Logout';
                      ...
                      
                      ...
                      
                      <Router>
                        <Navbar />
                        <Routes>
                          <Route path='/' element={<Home />} />
                          <Route path='/my-account' element={<Account />} />
                          <Route path='/login' element={<Login />} />
                          <Route path='/logout' element={<LogOut />} />
                          <Route path='/profile' element={<Profile />} />
                        </Routes>
                        <Footer />
                      </Router>
                      

                      How can I change this Navbar dropdown item to update from &quot;Login&quot; to &quot;Logout&quot; when a user logs in?

                      copy iconCopydownload iconDownload
                      {subNav.title==='Login'?(userLoggedIn?'Logout':'Login'):subNav.title}
                      
                      export const NavItemsList = [
                          ...
                          {
                              title: Account,
                              path: '/my-account',
                              cName: 'nav-links',
                              subNav: [
                                  {
                                      title: 'Login',
                                      path: '/login',
                                      cName: 'dropdown-link',
                                      menuName: 'account-menu',
                                      authenticated: false,
                                  },
                                  {
                                      title: 'Logout',
                                      path: '/logout',
                                      cName: 'dropdown-link',
                                      menuName: 'account-menu',
                                      authenticated: true,
                                  },
                                  {
                                      title: 'Profile',
                                      path: '/profile',
                                      cName: 'dropdown-link',
                                      menuName: 'account-menu',
                                  },
                              ],
                          },
                          ...
                      ];
                      
                      function Dropdown({ submenus }) {
                        const { user: currentUser } = useSelector((state) => state.auth);
                      
                        const [click, setClick] = useState(false);
                      
                        const handleClick = () => setClick(click => !click);
                      
                        return (
                          <ul
                            onClick={handleClick}
                            className={click ? 'dropdown-menu clicked' : 'dropdown-menu'}
                          >
                            {submenus
                              .filter(({ authenticated }) => {
                                if (authenticated !== undefined) {
                                  return !!currentUser === authenticated;
                                }
                                return true;
                              })
                              .map((subNav) => (
                                <div key={subNav.path} className={subNav.menuName}>
                                  <li className='dropdown-links'>
                                    <Link
                                      className={subNav.cName}
                                      to={subNav.path}
                                      onClick={() => setClick(false)}
                                    >
                                      {subNav.title}
                                    </Link>
                                  </li>
                                </div>
                              ))
                            }
                          </ul>
                        );
                      }
                      
                      export const NavItemsList = [
                          ...
                          {
                              title: Account,
                              path: '/my-account',
                              cName: 'nav-links',
                              subNav: [
                                  {
                                      title: 'Login',
                                      path: '/login',
                                      cName: 'dropdown-link',
                                      menuName: 'account-menu',
                                      authenticated: false,
                                  },
                                  {
                                      title: 'Logout',
                                      path: '/logout',
                                      cName: 'dropdown-link',
                                      menuName: 'account-menu',
                                      authenticated: true,
                                  },
                                  {
                                      title: 'Profile',
                                      path: '/profile',
                                      cName: 'dropdown-link',
                                      menuName: 'account-menu',
                                  },
                              ],
                          },
                          ...
                      ];
                      
                      function Dropdown({ submenus }) {
                        const { user: currentUser } = useSelector((state) => state.auth);
                      
                        const [click, setClick] = useState(false);
                      
                        const handleClick = () => setClick(click => !click);
                      
                        return (
                          <ul
                            onClick={handleClick}
                            className={click ? 'dropdown-menu clicked' : 'dropdown-menu'}
                          >
                            {submenus
                              .filter(({ authenticated }) => {
                                if (authenticated !== undefined) {
                                  return !!currentUser === authenticated;
                                }
                                return true;
                              })
                              .map((subNav) => (
                                <div key={subNav.path} className={subNav.menuName}>
                                  <li className='dropdown-links'>
                                    <Link
                                      className={subNav.cName}
                                      to={subNav.path}
                                      onClick={() => setClick(false)}
                                    >
                                      {subNav.title}
                                    </Link>
                                  </li>
                                </div>
                              ))
                            }
                          </ul>
                        );
                      }
                      

                      only one child route displaying in react? displays component for a different route instead of its own

                      copy iconCopydownload iconDownload
                      <div className="container mt-3">
                        <Switch>
                          <Route path="/login" component={Login} />
                          <Route path="/register" component={Register} />
                          <Route path="/profile" component={Profile} />
                          <Route path="/films/:title/:id" component={MovieDetailContainer}/>
                          <Route path="/films/:title" component={MovieListComponent}/>
                          <Route path="/user" component={BoardUser} />
                          <Route path="/creator" component={BoardCreator} />
                          <Route path="/admin" component={BoardAdmin} />
                          <Route path={["/", "/home"]} component={Home} />
                        </Switch>
                      </div>
                      

                      EventBus implementation using Coroutines and LiveData

                      copy iconCopydownload iconDownload
                      with(viewModel) {
                          eventsFlow.collectWhenStarted(viewLifecycleOwner, ::processEvents)
                      }
                      
                      inline fun <T> Flow<T>.collectWhenStarted(
                          lifecycleOwner: LifecycleOwner,
                          crossinline action: suspend (T) -> Unit
                      ): Job = lifecycleOwner.lifecycleScope.launchWhenStarted {
                          collectLatest {
                              action.invoke(it)
                          }
                      }
                      
                      val eventsFlow: Flow<DataClass> = flowEventBus
                          .flowMessage()
                          .shareIn(viewModelScope, SharingStarted.Lazily, 1)
                      
                      with(viewModel) {
                          eventsFlow.collectWhenStarted(viewLifecycleOwner, ::processEvents)
                      }
                      
                      inline fun <T> Flow<T>.collectWhenStarted(
                          lifecycleOwner: LifecycleOwner,
                          crossinline action: suspend (T) -> Unit
                      ): Job = lifecycleOwner.lifecycleScope.launchWhenStarted {
                          collectLatest {
                              action.invoke(it)
                          }
                      }
                      
                      val eventsFlow: Flow<DataClass> = flowEventBus
                          .flowMessage()
                          .shareIn(viewModelScope, SharingStarted.Lazily, 1)
                      
                      with(viewModel) {
                          eventsFlow.collectWhenStarted(viewLifecycleOwner, ::processEvents)
                      }
                      
                      inline fun <T> Flow<T>.collectWhenStarted(
                          lifecycleOwner: LifecycleOwner,
                          crossinline action: suspend (T) -> Unit
                      ): Job = lifecycleOwner.lifecycleScope.launchWhenStarted {
                          collectLatest {
                              action.invoke(it)
                          }
                      }
                      
                      val eventsFlow: Flow<DataClass> = flowEventBus
                          .flowMessage()
                          .shareIn(viewModelScope, SharingStarted.Lazily, 1)
                      

                      Generic Method in Java with out parameters

                      copy iconCopydownload iconDownload
                              public <T extends IntegrationEvent, TH extends IntegrationEventHandler<T>> void subscribe(java.lang.Class<T> tClass, java.lang.Class<TH> thClass) {
                      
                              }
                      

                      How can I configure my event bus in ASP.NET Core 6 - Migration to .NET 6

                      copy iconCopydownload iconDownload
                      var builder = WebApplication.CreateBuilder(args);
                      builder.Services.AddTransient<IEventBus,EventBus>();
                      
                      
                      ServiceProvider serviceProvider = builder.Services.BuildServiceProvider();
                      var eventBus = serviceProvider.GetRequiredService<IEventBus>();
                      eventBus.Subscribe<MessageSentEvent, MessageSentEventHandler>();
                      

                      Vert.x 4 eventbus serialize multiple classes with same codec

                      copy iconCopydownload iconDownload
                      fun main() {
                        val vertx = Vertx.vertx()
                        vertx.eventBus().registerCodec(GenericCodec())
                      
                        vertx.eventBus().consumer<Foo>("test-address") {
                          println(it.body())
                          it.reply(Bar(), genericDeliveryOptions)
                        }
                      
                        vertx.eventBus().request<String>("test-address", Foo(), genericDeliveryOptions) {
                          println(it.result().body())
                        }
                      
                        vertx.close()
                      }
                      
                      data class Foo(
                        val foo: String = "foo",
                      )
                      
                      data class Bar(
                        val bar: String = "bar",
                      )
                      
                      class GenericCodec : MessageCodec<Any, Any> {
                        companion object {
                          const val NAME = "generic"
                        }
                      
                        private val mapper: ObjectMapper = ObjectMapper()
                      
                        override fun encodeToWire(buffer: Buffer, s: Any) {
                          buffer.appendBytes(mapper.writeValueAsBytes(s))
                        }
                      
                        override fun decodeFromWire(pos: Int, buffer: Buffer): Any {
                          throw RuntimeException("should never get here, unless using clustered mode")
                        }
                      
                        override fun transform(s: Any): Any {
                          return s
                        }
                      
                        override fun name(): String {
                          return NAME
                        }
                      
                        override fun systemCodecID(): Byte {
                          return -1
                        }
                      }
                      
                      val genericDeliveryOptions = deliveryOptionsOf(codecName = GenericCodec.NAME)
                      

                      Using the mitt-library in Vue with Webpack hot-reload causes problems?

                      copy iconCopydownload iconDownload
                      // mitt.on('list_refresh', () => refresh()) ❌
                      
                      mitt.on('list_refresh', refresh) ✅
                      mitt.off('list_refresh', refresh)
                      
                      import { onMounted, onUnmounted } from 'vue'
                      
                      export default {
                        setup() {
                          const refresh = () => { /*...*/ }
                      
                          onMounted(() => mitt.on('list_refresh', refresh))
                          onUnmounted(() => mitt.off('list_refresh', refresh)) 👈
                        }
                      }
                      
                      // mitt.on('list_refresh', () => refresh()) ❌
                      
                      mitt.on('list_refresh', refresh) ✅
                      mitt.off('list_refresh', refresh)
                      
                      import { onMounted, onUnmounted } from 'vue'
                      
                      export default {
                        setup() {
                          const refresh = () => { /*...*/ }
                      
                          onMounted(() => mitt.on('list_refresh', refresh))
                          onUnmounted(() => mitt.off('list_refresh', refresh)) 👈
                        }
                      }
                      

                      Unable to Filter By Category in A Forum

                      copy iconCopydownload iconDownload
                      <v-btn text color="blue" @click="filterCategory(category.id)">{{category.name}}</v-btn>
                      
                      //...
                      
                      filterCategory(id) {
                          EventBus.$emit('filterCategory', id);
                      }
                      
                      computed: {
                          filteredQuestions() {
                              if (this.id) {
                                  return this.questions.filter(question => question.category_id === this.id)
                              }
                      
                              return this.questions;
                          }
                      },
                      
                      listen() {
                          EventBus.$on('filterCategory', (id) => { 
                              this.id = id;
                          })
                      },    
                      
                      <question v-for="question in filteredQuestions"
                      
                      <v-btn text color="blue" @click="filterCategory(category.id)">{{category.name}}</v-btn>
                      
                      //...
                      
                      filterCategory(id) {
                          EventBus.$emit('filterCategory', id);
                      }
                      
                      computed: {
                          filteredQuestions() {
                              if (this.id) {
                                  return this.questions.filter(question => question.category_id === this.id)
                              }
                      
                              return this.questions;
                          }
                      },
                      
                      listen() {
                          EventBus.$on('filterCategory', (id) => { 
                              this.id = id;
                          })
                      },    
                      
                      <question v-for="question in filteredQuestions"
                      
                      <v-btn text color="blue" @click="filterCategory(category.id)">{{category.name}}</v-btn>
                      
                      //...
                      
                      filterCategory(id) {
                          EventBus.$emit('filterCategory', id);
                      }
                      
                      computed: {
                          filteredQuestions() {
                              if (this.id) {
                                  return this.questions.filter(question => question.category_id === this.id)
                              }
                      
                              return this.questions;
                          }
                      },
                      
                      listen() {
                          EventBus.$on('filterCategory', (id) => { 
                              this.id = id;
                          })
                      },    
                      
                      <question v-for="question in filteredQuestions"
                      
                      <v-btn text color="blue" @click="filterCategory(category.id)">{{category.name}}</v-btn>
                      
                      //...
                      
                      filterCategory(id) {
                          EventBus.$emit('filterCategory', id);
                      }
                      
                      computed: {
                          filteredQuestions() {
                              if (this.id) {
                                  return this.questions.filter(question => question.category_id === this.id)
                              }
                      
                              return this.questions;
                          }
                      },
                      
                      listen() {
                          EventBus.$on('filterCategory', (id) => { 
                              this.id = id;
                          })
                      },    
                      
                      <question v-for="question in filteredQuestions"
                      

                      Community Discussions

                      Trending Discussions on EventBus
                      • How can I redirect a user to login when a certain link is clicked using JWT
                      • Every bean/class instance created twice in spring boot application
                      • How to list all consumers that are listening to an address on a vertex event bus?
                      • NuxtJS and event bus
                      • How do I implement a Logout functionality from a React Router Link to imports an array?
                      • How can I change this Navbar dropdown item to update from &quot;Login&quot; to &quot;Logout&quot; when a user logs in?
                      • only one child route displaying in react? displays component for a different route instead of its own
                      • EventBus implementation using Coroutines and LiveData
                      • Generic Method in Java with out parameters
                      • How can I configure my event bus in ASP.NET Core 6 - Migration to .NET 6
                      Trending Discussions on EventBus

                      QUESTION

                      How can I redirect a user to login when a certain link is clicked using JWT

                      Asked 2022-Apr-08 at 08:49

                      I am trying to make it so that when a user clicks on a certain Link (Upload Component), it will redirect them to to the login component and am not sure how to accomplish this task in React. I was directed to another answered question, but it hasn't helped me as I am still confused on what I need to do with my own set up. I understand I need to make my own protected route (maybe), but I saw others accessing useContext and I do not have any file with context. I am using Version 6 in react dom. I am also using React router and redux in my project so I know I need to access the state somehow, just not sure how to wrap my mind around it so if anyone could help, I would appreciate it. The user is being stored in local storage with JWT authentication.

                      App.js:

                      import React, {useState, useEffect, useCallback} from 'react';
                      import {useDispatch, useSelector} from 'react-redux';
                      import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'; //Switch was replaced by Routes in react-router-dom v6
                      import './App.css';
                      import Navbar from './components/Navbar';
                      import Footer from './components/Footer';
                      import Home from './components/pages/Home';
                      import Uploads from './components/pages/Uploads';
                      import Account from './components/pages/Account';
                      import Login from './components/pages/Login';
                      import LogOut from './components/Logout';
                      import Register from './components/pages/Register';
                      import Profile from './components/pages/Profile';
                      import EditProfile from './components/pages/EditProfile';
                      import BoardAdmin from './components/pages/BoardAdmin';
                      import BoardModerator from './components/pages/BoardModerator';
                      import BoardUser from './components/pages/BoardUser';
                      import {logout} from './slices/auth';
                      import EventBus from './common/EventBus';
                      
                      const App = () => {
                          const [showModeratorBoard, setShowModeratorBoard] = useState(false);
                          const [showAdminBoard, setShowAdminBoard] = useState(false);
                          const {user: currentUser} = useSelector((state) => state.auth);
                          const dispatch = useDispatch();
                      
                          useEffect(() => {
                              if (currentUser) {
                                  setShowModeratorBoard(currentUser.roles.includes('ROLE_MODERATOR'));
                                  setShowAdminBoard(currentUser.roles.includes('ROLE_ADMIN'));
                              } else {
                                  setShowModeratorBoard(false);
                                  setShowAdminBoard(false);
                              }
                          }, [currentUser]);
                      
                          return (
                              <>
                                  <Router>
                                      <Navbar />
                                      <Routes>
                                          <Route path='/' element={<Home />} />
                                          <Route path='/create/upload' element={<Uploads />} />
                                          <Route path='/my-account' element={<Account />} />
                                          <Route path='/login' element={<Login />} />
                                          <Route path='/logout' element={<LogOut />} />
                                          <Route path='/register' element={<Register />} />
                                          <Route path='/profile' element={<Profile />} />
                                          <Route path='/profile/edit' element={<EditProfile />} />
                                          <Route path='/user' element={<BoardUser />} />
                                          <Route path='/mod' element={<BoardModerator />} />
                                          <Route path='/admin' element={<BoardAdmin />} />
                                      </Routes>
                                      <Footer />
                                  </Router>
                              </>
                          );
                      };
                      
                      export default App;
                      

                      Auth.js:

                      import {createSlice, createAsyncThunk} from '@reduxjs/toolkit';
                      import {setMessage} from './messages';
                      import AuthService from '../services/auth.service';
                      const user = JSON.parse(localStorage.getItem('user'));
                      export const register = createAsyncThunk(
                          'auth/register',
                          async ({username, email, password}, thunkAPI) => {
                              try {
                                  const response = await AuthService.register(username, email, password);
                                  thunkAPI.dispatch(setMessage(response.data.message));
                                  return response.data;
                              } catch (error) {
                                  const message =
                                      (error.response &&
                                          error.response.data &&
                                          error.response.data.message) ||
                                      error.message ||
                                      error.toString();
                                  thunkAPI.dispatch(setMessage(message));
                                  return thunkAPI.rejectWithValue();
                              }
                          }
                      );
                      export const login = createAsyncThunk(
                          'auth/login',
                          async ({username, password}, thunkAPI) => {
                              try {
                                  const data = await AuthService.login(username, password);
                                  return {user: data};
                              } catch (error) {
                                  const message =
                                      (error.response &&
                                          error.response.data &&
                                          error.response.data.message) ||
                                      error.message ||
                                      error.toString();
                                  thunkAPI.dispatch(setMessage(message));
                                  return thunkAPI.rejectWithValue();
                              }
                          }
                      );
                      export const logout = createAsyncThunk('auth/logout', async () => {
                          await AuthService.logout();
                      });
                      const initialState = user
                          ? {isLoggedIn: true, user}
                          : {isLoggedIn: false, user: null};
                      const authSlice = createSlice({
                          name: 'auth',
                          initialState,
                          extraReducers: {
                              [register.fulfilled]: (state, action) => {
                                  state.isLoggedIn = false;
                              },
                              [register.rejected]: (state, action) => {
                                  state.isLoggedIn = false;
                              },
                              [login.fulfilled]: (state, action) => {
                                  state.isLoggedIn = true;
                                  state.user = action.payload.user;
                              },
                              [login.rejected]: (state, action) => {
                                  state.isLoggedIn = false;
                                  state.user = null;
                              },
                              [logout.fulfilled]: (state, action) => {
                                  state.isLoggedIn = false;
                                  state.user = null;
                              },
                          },
                      });
                      const {reducer} = authSlice;
                      export default reducer;
                      

                      It looks like adding the if statement in my upload file is making it so that a logged in user can access the h1 element that is in the file, but not an unauthenticated user. So its working to an extent, just not redirecting back to login.

                      Upload.jsx:

                      import React from 'react';
                      import {Link} from 'react-router-dom';
                      import {useSelector} from 'react-redux';
                      function Uploads() {
                          const {user: currentUser} = useSelector((state) => state.auth);
                          if (!currentUser) {
                              return <Link to='/login' />;
                          }
                          return (
                              <>
                                  <h1 className='page'>UPLOADS</h1>
                              </>
                          );
                      }
                      
                      export default Uploads;
                      

                      ANSWER

                      Answered 2022-Apr-08 at 08:49

                      Rendering the Link doesn't imperatively navigate, use the Navigation component.

                      Example:

                      import React, { useEffect } from 'react';
                      import { Navigate } from 'react-router-dom';
                      import { useSelector } from 'react-redux';
                      
                      function Uploads() {
                        const { user: currentUser } = useSelector((state) => state.auth);
                      
                        if (!currentUser) {
                          return <Navigate to='/login' replace />;
                        }
                        return (
                          <>
                            <h1 className='page'>UPLOADS</h1>
                          </>
                        );
                      }
                      
                      export default Uploads;
                      

                      Typically you would protect the route instead. If you wanted to do that:

                      import { Navigate, Outlet } from 'react-router-dom';
                      import { useSelector } from 'react-redux';
                      
                      const PrivateRoutes = () => {
                        const { user: currentUser } = useSelector((state) => state.auth);
                        return currentUser 
                          ? <Outlet />
                          : <Navigate to="/login" replace />;
                      }
                      

                      ...

                      <Routes>
                        <Route path='/' element={<Home />} />
                        <Route element={<PrivateRoutes />}>
                          <Route path='/create/upload' element={<Uploads />} />
                          ... any other protected routes ...
                        </Route>
                        ... other unprotected routes ...
                      </Routes>
                      

                      Source https://stackoverflow.com/questions/71793361

                      Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                      Vulnerabilities

                      No vulnerabilities reported

                      Install EventBus

                      You can download it from GitHub, Maven.
                      You can use EventBus like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the EventBus component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

                      Support

                      For more details please check the [EventBus website](https://greenrobot.org/eventbus). Here are some direct links you may find useful:.

                      DOWNLOAD this Library from

                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      Explore Related Topics

                      Share this Page

                      share link
                      Consider Popular Pub Sub Libraries
                      Try Top Libraries by greenrobot
                      Compare Pub Sub Libraries with Highest Support
                      Compare Pub Sub Libraries with Highest Quality
                      Compare Pub Sub Libraries with Highest Security
                      Compare Pub Sub Libraries with Permissive License
                      Compare Pub Sub Libraries with Highest Reuse
                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      • © 2022 Open Weaver Inc.