#Fetching data from different file

12 messages · Page 1 of 1 (latest)

fierce dirge
#

Hello. So I am making a quote site and the quotes are basically displayed on home page. The quotes info(quote, username of creator, avatar of creator....) are fetched from the database. Now I am trying to do when you press on the avatar that is on the card, a profile page opens. The profile page is basically dynamic and changes it's displayed user avatar, user username based on the quote avatar you click. Does someone know how I could transfer of fetch the data from let's say Card.tsx to Profile.tsx. If anyone could help me somehow I would love it.

hidden bronze
#

Add more details to the thread that you already have open.

neon mortar
#

I'm assuming Card.tsx and Profile.tsx are 2 different routes inside your application.

I can think of 2 ways to go with this at the moment:

  1. Use a context containing the avatar, the username. When you click on an avatar, you set this information in the context, open the Profile page and display the information that the context contains.

However I don't like this approach, since if you have to add more content to the Profile page, you'll have to pass those infos to the Card component, put them in the context and then access them from the Profile page. This isn't great in the long run.
For more info have a look at the context docs: https://it.legacy.reactjs.org/docs/context.html

  1. Inside the Card component, other than the avatar and the username, I would fetch an identifier for the user, like userId or something like that. You can then pass this userId inside the route as a parameter (have a look at dynamic segments https://reactrouter.com/en/main/route/route#dynamic-segments)

Then use this param inside the Profile.tsx component to make a specific API call to fetch the user's information.

fierce dirge
fierce dirge
hidden bronze
#

FWIW, I'd try to stick to prop passing before reaching for context.

neon mortar
#

Yeah for learning purposes I'd stick with props first, then move to more articulated things as contexts. I suggested it as a possible solution to not alter your project structure, but since you seem to be a beginner I'd go with the basics

fierce dirge
hidden bronze
#

Yeah, for me, it's not even really a "beginner" vs. "advanced" thing - I think context should be used very rarely.

neon mortar