简体   繁体   中英

Can't access redux state object's key in TypeScript

I am using typescript in Ionic along with React hooks, so I was adding my errorReducer in it which handles the error user gets from server in case anything goes wrong.

Here is my code below

Action

  import { ERROR_OCCURED } from "./types";
    export const errorActions = () => async (dispatch: any) => {
      console.log('err action triggered')
      dispatch({
        type: ERROR_OCCURED
      });
    };

Reducer

import { ERROR_OCCURED } from "../actions/types";
function fetchRedcuer(state = {}, action: any) {
  switch (action.type) {
    case ERROR_OCCURED:
      return {
        ...state,
         isauth:true
      };

    default:
      return state;
  }
}

export default fetchRedcuer;

then in my typescript component

import { useSelector, useDispatch } from "react-redux";
import React, { useState, useEffect } from "react";
import { userRegisterAction } from "../../src/redux/actions/user";
import { RootState } from "../redux/reducers";

type IUser = {
  error: { [isauth: string]: boolean };
};

const Signup: React.FC<IUser> = (props) => {
  const [state, setState] = useState<IUser>({
  error:{}
  });
  const dispatch = useDispatch();
  const error = useSelector((state: RootState) => {
    console.log(state.error);                     //here i get access to my state that is inside error reducer and also here i get error when i try to access boolean value
    return { error: state.error };   
  });
  console.log(error.error);
  return (
    <div>

    </div>
  );
};

export default Signup;

so on

console.log(state.error)

initally I get {} but then after the state has been updated i get

{isauth: true}

but then if i try to access this boolean value in useSelector by

console.log(state.error.isauth)

I get the typescript error which states

Property 'isauth' does not exist on type '{}'.

OR in simple words how do I tell TypeScript to somehow initially skip the empty object{} and not check for its key value pairs as updating state takes a little time

I recommend to stay consistent and instead of passing empty error object {}.

In error pass:

{ isauth: false; }

I believe Typescript is for that purpose only, to let you know your mistakes at early stage's. So everyone who looks at your component will know, the data you will be extracting(holding)!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM