skip to Main Content

i am try to fetch tha data from the api, the data is geting properly but while i set the data using state eg :- const data = setUser(data), than it’s showing the undefine

here is the code

import React, { useEffect, useState } from "react";
import axios from "axios";

// get request is placed here -------------------xxxxxxxxxxxxxxxxxxxx----------------------

function Student() {
  const [users, setUsers] =useState();

  useEffect(() => {
    async function getStu() {
      const res = await axios.get("http://localhost:5000/books");
      const data = res;
      setUsers(data)
      console.log(users)
    }
    getStu();
  }, []);

how to solve undefined error i watch so many youtube video but nothing is working

2

Answers


  1. setState() is an async function . using console.log() just right after setting the new state will render the previous value in your case undefined . To show the new state move it to another useEffect hook .

    useEffect(() => {
        console.log(users)
    
    }, [users])
    

    be aware when using axios , you send a request to the server it returns a response, Axios responses are objects. with data , status , StatusText , Headers … . if you want the payload that the server returned . you have to access data object in your case res.data .

    In your case change your code like this :

    useEffect(() => {
        async function getStu() {
          const res = await axios.get("http://localhost:5000/books");     
          setUsers(res.data)
          console.log(users)
        }
        getStu();
      }, []);
    
    Login or Signup to reply.
  2. There’s a few issues here.

    1. Initialise your state with the type of data you’re expecting in the request whether it’s an array or an object etc.

    2. You can’t immediately log an updated state as state updates are asynchronous and batched. Use a separate useEffect hook to log the state with the state listed in its dependency array.

    3. Axios returns an object with the API data as a value of the data property so you need to extract that.

      The other properties are the status/statusText etc which you may want to inspect to check that there isn’t an error with the response.

    function Student() {
      
      const [users, setUsers] = useState([]);
      // ---------------------------------^
      // Initialise state with an array
      
      useEffect(() => {
        async function getStu() {
          const res = await axios.get("http://localhost:5000/books");
          setUsers(res.data);
          // ---------^
          // Use the data value in the response object
        
        }
        getStu();
      }, []);
    
      useEffect(() => console.log(users), [users]);
      // ----^
      // Add a separate `useEffect` with `users` in its
      // dependency array
    
    ...
    
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search