Skip to content

Instantly share code, notes, and snippets.

@jasheloper
Last active March 27, 2022 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jasheloper/0e348ca8ccd45ccaebfca858fe61b4c8 to your computer and use it in GitHub Desktop.
Save jasheloper/0e348ca8ccd45ccaebfca858fe61b4c8 to your computer and use it in GitHub Desktop.
Dynamic Routing with Fetch API

Fetching Data from an API + using Dynamic Routing

Let's say I want to fetch data from an API but I also want to link each individual piece of data to its own individual page.

Import

import React, { useState, useEffect } from "react";

Component Setup Example

Shop.js

This component is going to grab API data to display in the shop.

function Shop() {



// USE EFFECT //

  useEffect(() => {
    fetchItems();
  }, []);
  
  
  
  
// STATE SETUP //

const [items, setItems] = useState([]);




// FETCH FROM API //

  const fetchItems = async () => {
    const data = await fetch("https://jsonplaceholder.typicode.com/users");
    const items = await data.json();
    
    console.log(items);
    
    setItems(items);
  };
  
  
  
  
  
// RETURN DATA // 

  return (
    <div>
      {items.map(item => (
        <h1 key={item.id}>
          <Link to={`/shop/${item.id}`}>{item.name}</Link>
          </h1>
      ))}
    </div>

  • In the return statement, we're mapping out the items array and returning each item as an <h1> link which will link to the specific item id.
  • Path: /shop/${item.id}
<Link to={`/shop/${item.id}`}>
  
    {item.name}
    
</Link>

Adding Path to Router

So, now we need actually add that path to the Router.

i.e.

<Route path="/shop/:id" component={ItemDetail} />
  • :id will take this path to the individual item.
  • We also need to decide which component is going to render out when an item is selected, in this case ItemDetail will render.

Component for Each Item

ItemDetail.js

This component will render when an individual item is clicked.

function Item({match}) {


// USE EFFECT //

  useEffect(() => {
    fetchItem();
    
    console.log(match)
  }, []);
  
  


// SET THE STATE //

  const [item, setItem] = useState({
  });
  
  
  
// FETCH INDIVIDUAL ITEM

  const fetchItem = async () => {
    const fetchItem = await fetch(`https://jsonplaceholder.typicode.com/users/${match.params.id}`);
    const item = await fetchItem.json();
    
    setItem(item);
    
    console.log(item);
  };
  
  
  
  
// RETURN STATEMENT //

  return (
    <div>
      <h1>{item.name}</h1>
      <h3>{item.username} | {item.email} </h3>
      <a href>{item.website}</a>

    </div>

  • Function Item takes in match
  • At the end of the URL we add ${match.params.id} which will give us that specific ID.
  • In the return we get the individual item's data.
@jasheloper
Copy link
Author

jasheloper commented Feb 27, 2020

@jasheloper
Copy link
Author

@jasheloper
Copy link
Author

jasheloper commented Feb 27, 2020

You may not want to Render ALL the data onto the original component, you may want to split that data up.

Let's say you have an API that contains for example:
- Users

You may not want to display EVERYTHING. You may want to maybe list maybe a little info about that user but someone must click to see more data about that user.

Dynamic Routing allows you to link to a specific piece of data (i.e. ID) which then can render out even more data about piece.

It's kind of like when you go to a real website shop and you see a list of items. Realistically, you don't see everything about that item. You usually see maybe a photo, a price, and a description.

Dynamic Routing helps keep your pages clean and organized by:

  • Only displaying what you want to display
  • Creating a dynamic route such as <Link to={/shop/${item.id}}>{item.name}</Link>
  • And then creating a path <Route path="/shop/:id" component={ItemDetail} />
  • And then creating a component to render out a path for a specific item.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment