The issue I have here is I am trying to retrieve the token in a JSON object that is being given as an argument in my saveToken function. Now Typescript cant recognize the object I am trying to retrieve so it gives me the error which you can see above in the title. Now I have assigned the argument as a JSON object as well as a regular JavaScript object but it does not seem to work.
How can I retrieve a specific object in a JSON object?
export default function useToken() {
const getToken = () => {
const tokenString = localStorage.getItem("token");
const userToken = JSON.parse(tokenString as string);
return userToken;
}
const [token, setToken] = useState(getToken());
const saveToken = (userToken: JSON) => {
localStorage.setItem("token", JSON.stringify(userToken));
setToken(userToken.token) // <--- error points to ".token"
}
return {
setToken: saveToken,
token
}
}
CodePudding user response:
So there are a few issues that I see with this code. First, interface JSON (userToken: JSON) is not correct. It should be userToken: string
. Though, I suspect in your case it should actually be userToken: values
. This would solve all your issues. As if it was a string, you're stringifying a JSON string. Though it depends on what you're passing in. If you're giving it a full values object, you'll need to change a few more things as the setItem would be setting the full values object. If it's only the userToken string, it requires no fixing, beyond the useless JSON.stringify that needs to be fixed regardless.