0

I am trying to populate Data from my API into my react form. When I console.log my get statement. I can see the array with the information which means my get is getting the information.

Image of my console log showing my array of data.

Now the issue is trying to use this array that I get back to populate fields- without specifying the array number.

'use client'

import {useEffect, useState } from 'react';
import Axios from "axios";

export default function Page() {
    const [user, setUser] = useState([])

const fetchData = () => { Axios.get('http://localhost:5000/api/v1/users', {
        headers: {
          'Content-Type': 'application/json'
        }, 
      }). then((res) => 
        {
            setUser(res.data)
            console.log(res.data)
        });
    }

   return (
        <div className='tutorial'>
            <h1 className='mb-4 text-2xl'>Data Fetching in React</h1>
            <button onClick={fetchData}>Search</button>
            
            <h2> Base: {JSON.stringify(user)}</h2>
            
        </div>
    )

I am going to need the information inside of the array so i can for example. Populate a dropdown or populate a name field by user from the API.

I have tried mapping and keying but I was not able to get what I needed. I also did try to

headers: {'Content-Type': 'application/json'},

I feel like I am close but I just cannot get my data to show up and use it without specifying the array number. Example: Data[0] or Data[1]. I want all my data back.

I want to get to an end goal where I can say for a field I want data.firstName and when I hit the search button I can get the firstname for either user.

7
  • do import axios from "axios" and also axios.get (in small cap) My question is do you want to show the response in <h2> tag? Commented May 15, 2024 at 18:50
  • Okay thanks for the correction! Yes, I am trying to show the response in >h2> tag. Just for testing purpose right now. Then once i confirm that it shows and my data from my array shows up on my UI. Then i can use that to fill in another form page i have created with fields like "FirstName" "LastName" and such. My issue now is getting my data for the array and using that to show in my form and UI page. Thanks @SayedulKarim Commented May 15, 2024 at 18:55
  • to show the response, First do call useEffect and inside of it call the fetchUser function. Then do map over the user (which you declare in useState) Commented May 15, 2024 at 19:01
  • So i called useEffect. useEffect(() => { fetchData },[]) Commented May 15, 2024 at 19:20
  • useEffect(() => { fetchData() },[]) Commented May 15, 2024 at 19:21

1 Answer 1

1

Try this. I think you're using Nextjs. But this is the React way. For initial test purposes, you can use that. later you can modify

    "use client"
    import { useEffect, useState } from 'react';
    import Axios from "axios";
    
    export default function Page() {
        const [users, setUsers] = useState([]);
        const [isLoading, setIsLoading] = useState(false);
        const [error, setError] = useState(null);
    
        useEffect(() => {
            const fetchData = async () => {
                setIsLoading(true);
                try {
                    const response = await Axios.get('http://localhost:5000/api/v1/users', {
                        headers: {
                            'Content-Type': 'application/json'
                        },
                    });
                    setUsers(response.data);
                } catch (error) {
                    setError(error.message);
                } finally {
                    setIsLoading(false);
                }
            };
    
            fetchData();
    
            // Clean-up function
            return () => {
                // Any clean-up code goes here, if needed
            };
        }, []); // Empty dependency array to trigger useEffect only once
    
        return (
            <div className='tutorial'>
                <h1 className='mb-4 text-2xl'>Data Fetching in React</h1>
                <button disabled={isLoading}> {isLoading ? 'Loading...' : 'Search'}</button>
                {error && <p>Error: {error}</p>}
                <h2>Users:</h2>
                <ul>
                    {users.map((user, index) => (
                        <li key={index}>
                            <p>Name: {user.name}</p>
                            <p>Email: {user.email}</p>
                        </li>
                    ))}
                </ul>
            </div>
        );
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Yea thank you so much, This helps. I am using Nextjs. Sorry i left that out. It populates some info now. Will figure out the rest. I appreciate your help Sir @Sayedul Karim

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.