Home > Enterprise >  Type Problem: How can useState(react-hook) be used as a global variable when contextAPI is used in t
Type Problem: How can useState(react-hook) be used as a global variable when contextAPI is used in t

Time:10-23

--Development environment: window10, VScode
--Tech: react --typescript

I only want to use contextAPI to manage the variables globally.(I don't use useReducer)
Variables are objects received from axios.

    const result = await axios.post('/register', {name,username,password})
        
    console.log(result.data);

I want to manage variables from the top component using useState.
But I can't do what I want because of the type problem.

// AuthContext.tsx
import {createContext, useContext} from 'react';

export type AuthType = {
    auth: object;
    setAuth: (a: object) => void;
}

export const AuthContext = createContext<AuthType>({
    auth: {a:1},
    setAuth: () => console.log('why not worked??')
})

export const useAuth = () => useContext(AuthContext);

I declared type of auth as an object to receive result.data(this variable is object).
In order to globally manage variables with useState hook, we wrote the following in the top-level component.

// App.tsx
import React,{useState} from 'react'
import styled from 'styled-components';
import ToolBar from './components/ToolBar';
import MainPage from "./pages/MainPage";
import LoginPage from "./pages/LoginPage";
import RegisterPage from "./pages/RegisterPage";
import { Switch, Route } from 'react-router-dom';
import { AuthContext, AuthType } from './contexts/AuthContext';

const Container = styled.div`
    max-width: 1200px;
    margin: 0 auto;
`;

function App() {
    const [auth, setAuth] = useState<AuthType>()
    return (
        <Container>
            <AuthContext.Provider value={{auth,setAuth}} >
                <ToolBar/>
                <Switch>
                    <Route path='/' component={MainPage} exact />
                    <Route path='/auth/register' component={RegisterPage} exact/>
                    <Route path='/auth/login' component={LoginPage} exact/>
                </Switch>
            </AuthContext.Provider>
        </Container>
    )
}
export default App

However, type error occurred at the value of property of the tag AuthContext.Provider
The contents are as follows.
the error of auth

Type 'AuthType | undefined' is not assignable to type 'object'. Type 'undefined' is not assignable to type 'object'.ts(2322)

the error of setAuth

Type 'Dispatch<SetStateAction<AuthType | undefined>>' is not assignable to type '(a: object) => void'. Types of parameters 'value' and 'a' are incompatible. Type 'object' is not assignable to type 'SetStateAction<AuthType | undefined>'. Type 'object' is not assignable to type '(prevState: AuthType | undefined) => AuthType | undefined'. Type '{}' provides no match for the signature '(prevState: AuthType | undefined): AuthType | undefined'.ts(2322)

I couldn't find any information and knowledge related to this. So I'd like to ask the seniors.
I'm sorry for the low level of questions.

CodePudding user response:

It seems you have undefined initial state. Additionally you are declaring the state type to be the entire context type when in actuality you are only storing the "auth" type, an object.

const [auth, setAuth] = useState<AuthType>(); // <-- undefined

Since you defined the auth state to be an object, provide an object as valid initial state and declare the type.

const [auth, setAuth] = useState<object>({}); // <-- empty object

CodePudding user response:

You declared <AuthType> for typescript and it is good but your hook is empty now!

if you wanna your hook to be an object so:

useState({})
  • Related