0

I am working on my first ReactJS project and I've been having trouble getting user data to return from an asynchronous function that calls an API for the database.

I've been struggling for a few days and so far I've tried the solutions from the following posts with little success:

  1. Uncaught Invariant Violation: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead
  2. Rendering an array.map() in React

So here's what my code originally looked like:

    const cookies = new Cookies(); 
    const userID = cookies.get("userID");
    const [userData, setUserData] = useState([]);  

    /**
      * Aysnchronous function to get user data. 
      * @returns User data from the database. 
      */
    const getData = async () => {

    const data = await axios.post("http://localhost:3001/userInfo",
     {ID: userID}).then((response) => {

        setUserData(response.data); 

     }).catch((err) => {

        console.log(err); 
     });

     return data; 
  }

  useEffect(() => {

    try{
    getData(); 
    }catch(err){

      console.log(err); 
    }
  }, []);


    return(

        <div className="box">
            
            <div>Welcome back {userData[0].firstName}!</div>
            
            </div> 
    );

At first, it was working, and the "Welcome back, user!" message was displaying but then about 10 minutes later the screen went white and I got this error in the console:

Uncaught Invariant Violation: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

I didn't entirely understand this, because the way I have it set up I thought this line was inputting the returned data into an array.

setUserData(response.data); 

So from here, I looked into the map function for js and rewrote my code with the added section just below the useEffect hook and above the return statement for the component:

 const userInfo = userData.map(user => {
   const ID = user.idusernames; 
   const email = user.email;
   const password = user.password; 
   const firstName = user.firstName; 
   const lastName = user.lastName; 

   return {
      ID, 
      email, 
      password, 
      firstName, 
      lastName
   }
   
  });

I then changed the welcome back statement to this:

<div>Welcome back {userInfo[0].firstName}!</div>

After doing this, everything seemed fine and the "Welcome back, user!" message started to display again. Unfortunately, a few minutes later, white screen and this error in the console instead:

Uncaught TypeError: Cannot read properties of undefined (reading 'firstName')

After this, I printed the userData and userInfo arrays to the console and they were both empty, so I have no idea what happened. At this point, I'm thinking there must be something wrong with the way I set up the async function since everything seems to just be timing out after previously working.

I appreciate any help you guys can offer.

2
  • 1
    Don't try to extract an element from the array when the array hasn't been populated yet - only do so after the API call finishes. Change your welcome statement's logic. Commented Aug 11, 2022 at 21:48
  • @CertainPerformance Ok, that makes sense. I'm trying to figure that out now with a ternary operator. It works every so often, but then it does the error again as if it's ignoring the operator. Commented Aug 11, 2022 at 22:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.