Search code examples
javascriptreact-nativereact-native-component

Component call does not display value


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);
    });
  };
}

Solution

  • 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

    import React from 'react';
    
    class Cias extends React.Component {
      componentDidMount() {
        const {valorToken} = this.props;
        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);
          });
      }
    }
    
    const CiasWrapper = () => {
      const {auth} = useAuth();
    
      return <Cias valorToken={auth.token} />;
    };
    
    export default CiasWrapper;
    

    but as a best practice, you should use functional components for hooks, you can implement the same behavior with a function component like

    import React, {useEffect, useState} from 'react';
    import {View} from 'react-native';
    
    const Cias = () => {
      const {auth} = useAuth();
      const [isLoading, setIsLoading] = useState(true);
      const [dataSource, setDataSource] = useState();
    
      useEffect(() => {
        fetch('https://url-test-test.es/api_movil/test.php', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${auth.token}`,
          },
          body: JSON.stringify({
            token: auth.token,
            id_marca: '5',
          }),
        })
          .then(response => response.json())
          .then(responseJson => {
            setDataSource(responseJson);
            setIsLoading(false);
          })
    
          .catch(error => {
            console.error(error);
          });
      }, []);
    
      return <View />;
    };
    
    export default Cias;
    

    you can read more about function components and hooks at react docs