Home > Mobile >  Data not rendering after OnCLick
Data not rendering after OnCLick

Time:07-05

I am trying to display the data after hitting the "Show the data" button. I can see the data in the console but it is not being display on the page. Could anyone help me out and guide me to let me know what is my mistake. Been struggling for days now. Below is my code. I have edited critical information in the code for obvious security reasons. Any help would be appreciated. Thank you.

axios.post is used to post the token and axios.get is used to fetch the data from the backend and display it.




import {useState} from 'react';
import axios from 'axios';
import '../App.css'

var raw = JSON.stringify({
  
  username: "xyz",
  password: "xyz"
});

const type_no = '88'; 

const URL = `example url://abc.com/abc/${type_no}`;




function getToken(){
  const promise = axios.post("example url://abc.com/", raw)
  const id = promise.then((response) => response.data.IdToken)
  return id
 };

const App = () => {
  const [data, setData] = useState({data: []});
  const [isLoading, setIsLoading] = useState(false);
  const [err, setErr] = useState('');




   const handleClick = async () => {
    getToken().then(token => {

        setIsLoading(true);
        
          const config = {
            headers: {
              'Authorization': 'Bearer '   token,
              'Content-Type': 'application/json',
            }
          };
          const {data} = axios.get(URL, config)
            .then((response) => {
              console.log(response);
              setData(response.data);
             
             
            })
            .catch((error) => {
              console.log(error);
            });
            setIsLoading(false)
      

        
    })

    
  

  };
  

  

  

  

  console.log('Data: ', JSON.stringify(data,null,4));   

  

  return (
    <div className="form">
      {err && <h2>{err}</h2>}

      <button onClick={handleClick}>Show the data</button>

      {isLoading && <h2>Loading data...</h2>}  

      {data.data?.map(data => {
        return (
          
          <div key={data.id}>
            <h2>{data.email}</h2>
            <h2>{data.first_name}</h2>
            <h2>{data.last_name}</h2>
            <br />
          </div>
        );
      })}
    </div>
  );

  
};

export default App;

CodePudding user response:

You've initialized the state data with { data: [] } but after fetching the data you're directly setting the state. Use setData({data: response.data}) instead of setData(response.data)

import {useState} from 'react';
import axios from 'axios';
import '../App.css'

var raw = JSON.stringify({
  username: "xyz",
  password: "xyz"
});

const type_no = '88'; 

const URL = `example url://abc.com/abc/${type_no}`;

function getToken(){
  const promise = axios.post("example url://abc.com/", raw)
  const id = promise.then((response) => response.data.IdToken)
  return id
 };

const App = () => {
  const [data, setData] = useState({data: []});
  const [isLoading, setIsLoading] = useState(false);
  const [err, setErr] = useState('');

  const handleClick = async () => {
    getToken().then(token => {
        setIsLoading(true);
          const config = {
            headers: {
              'Authorization': 'Bearer '   token,
              'Content-Type': 'application/json',
            }
          };
          const {data} = axios.get(URL, config)
            .then((response) => {
              console.log(response);
              setData({data: response.data});
            })
            .catch((error) => {
              console.log(error);
            });
            setIsLoading(false)
    })
  };

  console.log('Data: ', JSON.stringify(data,null,4));   

  return (
    <div className="form">
      {err && <h2>{err}</h2>}

      <button onClick={handleClick}>Show the data</button>

      {isLoading && <h2>Loading data...</h2>}  

      {data.data?.map(data => {
        return (
          
          <div key={data.id}>
            <h2>{data.email}</h2>
            <h2>{data.first_name}</h2>
            <h2>{data.last_name}</h2>
            <br />
          </div>
        );
      })}
    </div>
  );
};

export default App;

  • Related