I have a demo here
It's a React app using Typescript and hooks to capture entries into form that are simple displayed below.
Here in Stackblitz it works but locally I am using VS code and I get an error for setUser(userData);
the error is
const userData: { username: string; password: string; prevState: null; } Argument of type '{ username: string; password: string; prevState: null; }' is not assignable to parameter of type '(prevState: null) => null'. Type '{ username: string; password: string; prevState: null; }' provides no match for the signature '(prevState: null): null'.ts(2345)
How can I fox this typescript error
The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.
The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.
const [user, setUser] = useState(null);
Since you havn't given this a type, typescript has to try to infer it. It sees you passed in a null, so it assumes this state is (and always will be) null. Instead, you need to specify the type, as in:
interface UserData { username: string; password: string; prevState: null } //... const [user, setUser] = useState<UserData | null>(null);
If you fetching data from API you need this:
import React, { useState, useEffect } from 'react' import axios from 'axios'; const MyComponent = () => { const [data, setData] = useState<any | null>(null); const fetchData = () => { (...) //Axios.get() or async if u await data. setData(fetchData) } } useEffect(() =>{ fetchData() }, [])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With