Thinh Pham
Thinh Pham

Reputation: 21

How to properly passing data through functional component in ReactJS?

I am new to react and this is very confusing to me. Any help would be appreciated.

So I have an Axios Interceptor, making sure the user is authenticated, but that not the issue, the issue is the ".then()" part of the interceptor. So I am trying to pass "res" into my functional component "Profile" like below.

export function GetProfiles(history) {
    axiosInstance(history)
        .get('/profile')
        .then((res) => <Profile userData={UserProfile(res)} />)
        .catch((err) => console.log("err", err));
}

So this is how to write my "UserProfile(res)" function

function UserProfile(props) {
    let data = {
        firstName: props.data.firstName,
        lastName: props.data.lastName,
        email: props.data.email,
        phone: props.data.phone,
    };
    return { data };
}

export default UserProfile;

If I do console.log(data) in "UserProfile" I get all the data I needed. So everything is working as intended. However, when I try to retrieve those same data in the "Profile" component I get "undefined". So this is how I write my "Profile" component

function Profile({ userData }) {
    console.log(userData);
}
export default Profile;

Again, any help would very much appreciate, I am new to this so there is a very big chance I am doing it wrong. Please point me in the right direction.

Upvotes: 2

Views: 1426

Answers (2)

Rodrigo
Rodrigo

Reputation: 481

When you are fetching data from an API, normally you'd assign the response (res) to a variable, that way you separate the View (The component structure) from the Data (The user info from the API). So, in your case, you'd have to:

  1. Define a variable to store the user data.
  2. After that, inside the getProfile function, assign the response to the variable.
  3. And finally, pass the variable as a prop to your component.

You can use this code as an example:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
 
function App() {
  const [profileData, setProfileData] = useState();
 
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        'yourapiurl/profile',
      );
 
      setProfileData(result.data);
    };
 
    fetchData();
  }, []);
 
  return (
    <>
      <Profile userData={profileData} />
    </>
  );
}
 
export default App;

In this example, I'm using React Hooks, so you do your API call inside the useEffect hook. I defined a variable called profileData, where I will store the data from the API. Inside the fetchData function, I call the method setProfileData, so all the data that you got from the API will be stored inside the profileData variable. Finally, you pass the profileData as a prop to your Profile Component, and it will update as soon as the data is fetched from your API.

I got all the information from this link:

https://www.robinwieruch.de/react-hooks-fetch-data

In case you are using Class Components and not React Hooks, the process is very similar, just instead of defining the variable like this:

const [profileData, setProfileData] = useState();

You'd have to define it as the state of your component:

state = {
    profileData: []
  }

More info about how to fetch data from an API using Axios in React Class Components in the following link:

https://www.digitalocean.com/community/tutorials/react-axios-react

I hope this info was useful.

Happy Hacking!

Upvotes: 2

Hyetigran
Hyetigran

Reputation: 1215

I think you're trying to write UserProfile as a helper function but instead it looks like a function component the way you have it. You could map data in the .then chain before passing it down to your Profile component i.e.

let userData = userProfile(res);
return <Profile userData={userData} />

Upvotes: 1

Related Questions