1

I am making a call to my API in a react component. I am using the useState hook. I can make my API call and set my state. When I console.log my state after setting it, it is coming back undefined. My code is below:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { API } from '../../config';
import Layout from '../../components/Layout';

const PendingUser = () => {
  const [pendingUser, setPendingUser] = useState({
    firstName: '',
    lastName: '',
    email: '',
    leAgency: ''
  });

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

  const getPendingUsers = async () => {
    const { data } = await axios.get(`${API}/admin/pendinguser`);
    const pendingUsers = data;
    setPendingUser({
      firstName: pendingUsers.firstName,
      lastName: pendingUsers.lastName,
      email: pendingUsers.email,
      leAgency: pendingUsers.leAgency
    });
    console.log(pendingUser);
  };

  return (
    <table style={{ width: '100%' }}>
      <thead>
        <tr>
          <td>First Name</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>{pendingUser.firstName}</td>
        </tr>
      </tbody>
    </table>
  );
};

export default PendingUser;
Fabio Lopez
  • 517
  • 2
  • 5
  • 15
timbo245
  • 175
  • 1
  • 14
  • State setter functions are in most cases asynchronous, so don't expect the state variable to change on the next line. So if your question is why you don't see the changes right away, that's the answer. – codemonkey Mar 16 '21 at 00:25
  • Do you only have one pending user in your response data? Usually response data from an Axios call like that results in an array of objects that you can then map over and render inside a component. – cpppatrick Mar 16 '21 at 00:25
  • 3
    Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – codemonkey Mar 16 '21 at 00:28

1 Answers1

0

The setPendingUser call is done asynchronously. This is why right after you make the call you don't immediately get the value inside pendingUser.

If you want to know what's in the state each render, I suggest putting the console.log just before the return:

  console.log(pendingUser);
  return (
    <table style={{ width: '100%' }}>
    
Fabio Lopez
  • 517
  • 2
  • 5
  • 15