Home > Mobile >  useState data:null after fetching API data and set to useState
useState data:null after fetching API data and set to useState

Time:06-22

My purpose is to create a fetching function and return useState Data and use this function in other component.

It's fine to console.log (response.data). However, when I console.log useState "Data" it's show nothing after fetching data. Can anybody tell me why and how to solve it?

import axios from "axios";
import { useState} from "react";


const FetchPost = async () => {

    const [Data, setData] = useState(null)

    try {
        const response = await axios.get('url/api/blogs')
        .then(console.log(response.data))
        .then(setData(response.data))
        console.log (`this is useState data:${Data}`) 
        
      } 
      
    catch (error) {
        console.error(error);
      }

      return Data  
}

export default FetchPost

CodePudding user response:

make sure to run your FetchPost() function insie a useEffect hook wherever you are calling it, example :

useEffect(()=>{
    FetchPost();
  },[]);

CodePudding user response:

You can't use await & then together. Please replace your try-catch code with the below-

try {
        const response = await axios.get('url/api/blogs')
        console.log(response);
        setData(response.data) 
        
      } 
      
    catch (error) {
        console.error(error);
      }

Now, console.log(Data) outside of try-catch. First you will see null & then a value in Data.

  • Related