React Reduxjs toolkit is not reading state in useSelector, using Typescript. Is shows me an error that loggedIn is not a boolean

Viewed 299

I'm passing to the component a state from store.tsx file and it shows me an error. Error is in const loggedIn that state.loggedIn.loggedIn is not a boolean. Below is the code for component

  import React from "react";
import { StyledNavBar, StyledNavButton } from "./styles";
import { useSelector } from "react-redux";

export const NavBar = () => {
  interface IisLoggedInProp {
    loggedIn: boolean;
  }

  **const loggedIn = useSelector(
    (state: IisLoggedInProp) => state.loggedIn.loggedIn
  );**

  return (
    <StyledNavBar>
      <StyledNavButton>Dodaj Post</StyledNavButton>
      {loggedIn && <StyledNavButton>Dodaj Komentarz</StyledNavButton>}
      <StyledNavButton>Toggluj kolory</StyledNavButton>
      <StyledNavButton>Wyślij wiadomość</StyledNavButton>
    </StyledNavBar>
  );
};

And this is how store.js looks like I have cancelled logOutSlice from provided code to don't make confusion.

 import { createSlice, configureStore } from "@reduxjs/toolkit";

const initialLoggedInState = {
  loggedIn: false,
};

const loggedInSlice = createSlice({
  name: "loggedIn",
  initialState: initialLoggedInState,
  reducers: {
    withLogIn(state) {
      state.loggedIn = true;
    },
    withoutLogIn(state) {
      state.loggedIn = false;
    },
  },
});

export const loggedInActions = loggedInSlice.actions;   

export const store = configureStore({
  reducer: { loggedIn: loggedInSlice.reducer, logOut: logOutSlice.reducer },
});
2 Answers

useSelector always reads from your root state, so instead of IisLoggedInProp you have to use your RootState type there.

the state type is RootState

Do it this way

const loggedIn = useSelector(
    (state: RootState) => state.loggedIn.loggedIn
  );
Related