Search code examples
javascriptreactjsaxiosfetchsetstate

useState stays undefined after axios get fetch


I've cut down the code to the needed parts.

getArticleFromApi gets called onSubmit (apiData works fine)

My Problem ist that the console.log returns undefined after the FIRST click of submit.

if i hit it AGAIN a few Seconds later everything works as expected.

My Question is how can i make JS wait until article is no longer undefined. Until state article is set. (delay execution of code)

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

const [apiData, setApiData] = useState();
const [article, setArticle] = useState();

const getArticleFromApi = () => {
    axios.get('http://localhost:8080/api/articles/' + apiData.brand_id + '/' + apiData.article_number)
    .catch(err => console.log(err))
    .then(resp => {
      setArticle(resp.data.data)
    })
    console.log(article)
}

This is my first Question so go soft on me. Tell me if i can improve anything.


Solution

  • Since setState is a asynchronous function, you can not get a newly changed state right after setState.

    Check out offical docs about this topic.

    One way to log the changing of the state is to set a useEffect function with article.

    const getArticleFromApi = () => {
        axios.get('http://localhost:8080/api/articles/' + apiData.brand_id + '/' + apiData.article_number)
        .catch(err => console.log(err))
        .then(resp => {
          setArticle(resp.data.data)
        })
    }
    
    useEffect(() => {
        console.log(article)
    }, [article])
    

    Every time article changes, useEffect will run the callback function, which will log the latest article.