I am building a picker with data taken from a database. It works fine, but I can't send the value I have stored in auth.token
(in the useAuth
component) to the URL. I have tried in many ways and I am not able, can you tell me how I can?
//Call
import useAuth from "../hooks/useAuth";
const ValorToken = () => {
const { auth } = useAuth();
const valorToken = auth.token;
return (valorToken)
};
export default class Cias extends Component {
componentDidMount() {
return fetch('https://url-test-test.es/api_movil/test.php', {
method: 'POST',
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${ValorToken}`,
},
body: JSON.stringify({
token: ValorToken,
id_marca: '5'
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
}, function() {});
})
.catch((error) => {
console.error(error);
});
};
}
Basically, useAuth is a react hook that depends on react core hooks (
useState
,useEffect
, ...) so it should get called only in a function component.Here is another implementation if you want this kind of behavior (getting value from a react hook in a class component
but as a best practice, you should use functional components for hooks, you can implement the same behavior with a function component like
you can read more about function components and hooks at react docs