DEV Community

Cover image for Fetch within Fetch !
Jaspreet kaur
Jaspreet kaur

Posted on

Fetch within Fetch !

For my last project, I had to display some information for which I had to fetch requests within fetch request.

As you can see, in my database structure, I had a project data which has a user_id related to that project and tasks that belongs to that project. This information in the database is being collected from 3 different tables projects, users, and tasks using association and serialization.
(Just for information, I am using ruby on rails for backend and react for frontend).
Image description

Below is the data I wanted to display. As you can notice, I wanted to display user name (Assigned member) instead of user_id and related tasks content.

Image description

Now, in order to achieve above, I had to work with fetch requests in such a way that it gets the user data for the user_id related to that particular project as well as tasks for that project.

In code below,

  1. First its fetching the particular project data and setting the project state to that project.

  2. In order to get the tasks, setting the projectTask state to project.tasks (this will give us the tasks array, you can console.log to check ) within that fetch request. And then you can display content inside return using tasks.content .

  3. Now for the member info, we can only get the user_id from the current data structure, so in order to get the name we need to fetch the particular user's data which is related to the project being fetched(fetch(/users/${project.user_id})),

If you fetch users outside the project fetch request, it will give you unrelated user data which is not relevant to that project since that will be an independent fetch request not related to any project. So for a particular user's info, you need to fetch inside the project's fetch since there you can grab that project's id and user_id related to project.
This will fetch you the users' data of the user_id in that specific project and you can use user.name to display the name. This is just an example. Check the code below -

function DetailedProjectView (){
    const [project,setProject] = useState({});
    const [projectTasks, setProjectTasks] = useState([])
    const [user, setUser] = useState ({})
    const { id } = useParams();

    useEffect (()=> {
        fetch (`/projects/${id}`)
        .then (res=> res.json())
        .then (project => {
            setProject(project);
            setProjectTasks(project.tasks);
            console.log(project.tasks)
            console.log(project.user_id)
            fetch (`/users/${project.user_id}`)
            .then (res=> res.json())
            .then (user => setUser(user))
        })},[id]);

return (
   <> 
    <Card width={'100%'} align='center'>
        <CardHeader>
            <Heading size='md'>{project.project_title}</Heading>
        </CardHeader>
        <CardBody>
            <Text>{project.detail}</Text><br></br>
            <Text fontFamily={"cursive"}><b>Assigned Member: </b></Text>
            <Text>{user.first_name}</Text><br></br>
            <Text fontFamily={"cursive"} ><b>List of Tasks:</b> </Text>
            <OrderedList>
                {projectTasks.map((task) => {
                    return (
            <ListItem key={task.id}>{task.content}</ListItem>
             )})}
             </OrderedList>
        </CardBody>
    </Card>     
    </>
)}
Enter fullscreen mode Exit fullscreen mode

Hope, this helped someone who is a newbie like me to the coding world! When i was working on this problem, I couldn't find relevant answers on google. So, I thought to write this in my blog and help someone who is still learning to code like me. There must be for sure better ways to do this but this is what worked for me at that time.

Top comments (0)