First of all I'm a newbie in all frontend-aspects, so please excuse that the answer to this questions is probably just, that I am dumb. However I have to implement a way that users can change their passwords.
There is already a useToken.js file, which looks like this:
import { useState } from 'react';
export default function useToken() {
// Checks storage for existing token.
const getToken = () => {
var tokenString = '';
tokenString = sessionStorage.getItem('token');
if (tokenString === null) {
tokenString = localStorage.getItem('token');
}
const userToken = JSON.parse(tokenString);
return userToken?.token
};
const [token, setToken] = useState(getToken());
const saveToken = userToken => {
sessionStorage.setItem('token', JSON.stringify(userToken));
setToken(userToken.token);
};
return {
setToken: saveToken,
token
}
}
So I tried creating a function, which uses the useToken function to send out the API- authentication credentials.
import React, {Component, useState} from 'react';
import useToken from '../security/useToken';
async function ChangeUserPassword(credentials){
return fetch('https://api.testsite.de/change-password/', {
method: 'PUT',
headers: {
'Authorization': 'JWT ' + useToken(),
'Content-Type':'application/json'
},
body: JSON.stringify(credentials)
})
.then(data => data.json)
}
export default function ChangePassword(){
const[old_password, setOldPassword] = useState();
const[new_password, setNewPassword] = useState();
const handleSubmit = async e =>{
e.preventDefault();
const creds = await ChangeUserPassword({
old_password,
new_password
});
}
The handleSubmit-function is called on a button press and the old_password and new_password from input fields.
When I try to run it, it gives me this an 'Unhandled Rejection Error', saying Hooks can only be called inside the body of a functional Component. So I changed the location of the useToken -call to inside the body of my function, but this give me exactly the same error.
async function ChangeUserPassword(credentials){
const [token, setToken] = useState(useToken());
return fetch('https://api.zvconnect.de/change-password/', {
method: 'PUT',
headers: {
'Authorization': 'JWT ' + token,
'Content-Type':'application/json'
},
body: JSON.stringify(credentials)
})
.then(data => data.json)
}
You have to put your useState on the main component example:
const SampleApp = () => {
const [state1, setState1] = useState;
const [state2, setState2] = useState;
const MyFunction1 = () => {
.....
}
const MyFunction2 = () => {
.....
}
return(
<div></div>
)
}
export default SampleApp;
You can only use hooks inside components and other hooks, not inside a normal function.
You can't use it inside ChangeUserPassword()