I have this definition
export interface user{
email:string
name:string
last_name:string
}
export type UserType= {
user: user;
setUser:(user:user) => void;
}
const [user,setUser] = useState <user> ({
email:"",
name:"",
last_name:"",
})
export const UserContext = createContext <UserType>({user,setUser});
Then in App.tsx
function App() {
const [user,setUser] = useState <usuario> ({
email:"",
name:"",
last_name:"",
})
return
(
<UserContext.Provider value={ {user,setUser} } >
<Home/>
<About/>
</UserContext.Provider>
)
}
export default App
At home there is the problem because I need to set the email so:
export const Home= () => {
const {user,setUser} = useContext(UserContext)
/*....... Some code*/
setUser((state) => ({ ...state, email: email.current }))
}
whith the sentence setUser((state) => ({ ...state, email: email.current }))
An argument of type "(state: any) => any" cannot be assigned to a parameter of type "user". The type "(state: any) => any" is missing the following properties of the type "user": email, name and last_name.
and it does not work with this: setUser((state:user) => ({ ...state, email: email.current }))
CodePudding user response:
Your current definition of setUser
ignores the ability to pass a function. You'll need to define the setUser
type to be identical to the one produces from useState
:
import { SetStateAction, Dispatch } from 'react';
export interface UserType {
user: User;
setUser: Dispatch<SetStateAction<User>>;
}