Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

228
Views
React - Hooks, why is this implementation not working?

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)
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
about 4 years ago · Juan Pablo Isaza Report

0

You can only use hooks inside components and other hooks, not inside a normal function.

You can't use it inside ChangeUserPassword()

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!