Home > Software engineering >  Making fetch data clickable
Making fetch data clickable

Time:10-01

Task: "Write a simple React application that fetches the data from the selected API and displays it as a list/table. When clicking on an item in the list/table, more deatils about that item should be displayed. Details about the item should be fetched by clicking on that item and displayed on a separate page."

So far I've managed to fetch data from the selected API and display it as a list. Any ideas how do I make second part of task? Here's the code:

import React from "react";
import './App.css';

class App extends React.Component {

constructor(props) {
    super(props);

    this.state = {
        items: [],
        DataisLoaded: false
    };
}

componentDidMount() {
    fetch("https://api.thecatapi.com/v1/breeds")
        .then((res) => res.json())
        .then((json) => {
            this.setState({
                items: json,
                DataisLoaded: true
            });
        })
}
render() {
    
    const { DataisLoaded, items } = this.state;
    if (!DataisLoaded) return <div>
        <h1> Pleses wait some time.... </h1> </div> ;

    return (
    
    <div className = "App">
            <h1> Fetching data from an TheCatApi </h1>  {
            items.map((item) => (
        
            <ul> 
                <li>
                    { item.name }
                                      
                
                    
                </li>
                

              
              

            </ul>
            ))
        }
    </div>
);

} } export default App;

CodePudding user response:

You'll need to use Link.

<Link to="/yourPageDetail   item.(info you're sending over) ">
                <ul> 
                <li>
                    { item.name }                    
                </li>
            </ul>
</Link>

You'll also need to use "useparams" on the "yourPageDetail" to capture the ... item.(info you're sending over).

If you need more details I'm happy to share a project repository. lmk

CodePudding user response:

  1. Wrap each li tag in an a tag to redirect to /new-page when the item is clicked
  2. Add an onClick event to each li tag to save the item to localStorage when it's clicked

App.js

const App = () => {
    const [items, setItems] = useState([]);
    const [isLoading, setIsLoading] = useState(false);

    const handleCatRedirect = (cat) => {
      const handleClick = () => {
        localStorage.setItem("cat", JSON.stringify(cat));
      }

      return handleClick;
    }

    useEffect(() => {
        const fetchCats = async () => {
            setIsLoading(true);
            
            const res = await fetch("https://api.thecatapi.com/v1/breeds")
            const data = await res.json();

            setItems(data);
            setIsLoading(false);
        };

        fetchCats();
    }, []);

    if(isLoading)
        return <div>Loading...</div>

    return (
        <div className="App">
            <h1>Fetching data from an TheCatApi</h1>  
            <ul> 
              {items.map(item => (
                <a href="/new-page">
                  <li onClick={handleCatRedirect(item)}>
                    {item.name}                                      
                  </li>
                </a>
            ))}
          </ul>
        </div>
    );  
};
  1. On /new-page, load the cat from localStorage into the state to use on that new page.

NewPage.js (/new-page)

const NewPage = () => {
    // Load cat from localStorage when /new-page mounts 
    const [cat, setCat] = useState(() => {
        const cat = localStorage.getItem("cat");

        if(!cat)
            return null;
        
        return JSON.parse(cat);
    });

    // Display cat details on new page

    return (
        <>
        
        </>
    )
};
  • Related