Joey
Joey

Reputation: 121

Undefined inside useEffect

I am trying to fetch Api through axios call, using useContext embedded inside endpoint. Before axios call the userData return value, but inside the useEffect it is undefined, and I have no idea why this is happening.

The part that will interest you guys since I have imported everything and so on

    /* Importing UseState, UseEffect */
import React, {useState, useEffect, useContext} from "react";
/* Importing Axios */
import axios from "axios";
/* Styles Import */
import "./Badges.styles.scss";

/* Context Imports */
import {UserContext} from "../../../context/UserContext";


const Badges = () => {
 
  /* Axios call for badges starts */
    /* Creating the UseState for the badges */
    const {userData} = useContext(UserContext);
    console.log(userData);
    const [badges, setBadges] = useState()
    const [loading, setLoading] = useState(false)
    // /* Function to fetch the Api */
    //  /* Making the Axios call */
    useEffect(()  => {
      console.log(userData)
      axios.get(`/api/v1/user/gamification/${userData._id}`)
      .then(res => {
        setBadges(res.data);
      })
      .catch(err => console.log(err))
    },[])

  
   
   
  /* Axios call for badges ends */
    
  return ( .....

Upvotes: 0

Views: 262

Answers (2)

wowandy
wowandy

Reputation: 1302

Most likely, the hook with which you get userData does not have time to return the value you need before useEffect is triggered. If you need to execute a request every time userData changes, just add it to the useEffect dependency array, if only once, then in addition to the last step, add a check if the request has already been started

Upvotes: 1

Shyam
Shyam

Reputation: 5497

useEffect(()  => {
   // assuming your userData is null initially
      if(userData) 
     {
      axios.get(`/api/v1/user/gamification/${userData._id}`)
      .then(res => {
        setBadges(res.data);
      })
      .catch(err => console.log(err))
      } 
    },[userData])

Upvotes: 1

Related Questions