Home > OS >  can't use the usestate function to set variable value
can't use the usestate function to set variable value

Time:06-24

Please anyone can help to explain why my function is not work?

First, I create a function to Fetch post data from Strapi post as below:

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

const FetchPost = async () => {

    const [Data, setData] = useState(null)
    const [error, setError] = useState(null)
    console.log (`this is useState data:${Data}`) 

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

      return {Data, error}  
      
}

export default FetchPost

And would like to call this function in component and console the fetch data as below. But

const BlogMain = () => {
     
   const {Data, error} = FetchPost();
  
   console.log (`This is own function fetch in main page: ${Data}`)

    return (

)

export default BlogMain

Below is console fetching data:

Object
config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data: {data: Array(3), meta: {…}}
headers: {content-length: '9398', content-type: 'application/json; charset=utf-8'}
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: "OK"
[[Prototype]]: Object  

However, when I useState to set the Data and console it. It shows 'undefined'

Is there any person can explain this?

CodePudding user response:

Your FetchPost function is asynchronous, so it will return a value that is initially undefined, and will then change the value when the fetch request returns with a response.

In order to react to this value change, wrap the code that waits for the fetch result with useEffect:

const {Data, error} = FetchPost();
useEffect(
  () => console.log(`This is own function fetch in main page: ${Data}`), 
  [Data]
);

CodePudding user response:

You should set your data like so

setData(response.data.data)

Because the first data is for axios and the second one for your JSON schema

  • Related