简体   繁体   中英

Type Problem: How can useState(react-hook) be used as a global variable when contextAPI is used in typescript?

--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.

It seems you have undefined initial state.

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

Since you defined it to be an object, provide an object as valid initial state.

const [auth, setAuth] = useState<AuthType>({}); // <-- empty object
you declare <AuthType> for type script and it is good
but your hook is empty now!
if you wanna your hook be an object so write ====>useState({});<====

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