lisavanmansom / dropandheal-react

https://dropandheal-react.vercel.app/
0 stars 0 forks source link

Data fetch #13

Closed lisavanmansom closed 1 week ago

lisavanmansom commented 1 week ago

Data fetchen

Different Ways to Fetch Data in React

1. SWR method

This method is used to fetch data from a server and is used in React. It manages any issues that may arise when obtaining the data and helps you manage its storage. SWR includes useState() and useEffect(), so there is no need to import them.

The advantages of SWR:

How to use SWR to get data:

2. JavaScript Fetch() method

The fetch() method is well-known for retrieving data from APIs. It is recognized as the simplest and most used approach.

The advantages of using the fetch() method:

How to use fetch() to get data:

Inside useEffect(), we fetch our data by sending a request with the API key. The response comes back in JSON (JavaScript Object Notation).

In the return statement, we process the received photos by utilizing a map() function to iterate through each item.

In our specific scenario, we are only interested in the photos. We render them in the browser by displaying them in the main file of the application, or root. The main file could be App.jsx or Index.js.

https://www.freecodecamp.org/news/how-to-fetch-api-data-in-react/

lisavanmansom commented 1 week ago

Code uitwerking

Fetch.jsx

Om data te fetchen maak ik gebruik van een Fetch.jsx component, hier fetch ik data van de API en worden daar article's van gemaakt. Om een taak te renderen maak ik gebruik van map die de task state overschrijft (an array of task object). Ik render de title en de description in de article, voor beide maak ik gebruik van dangerouslySetInnerHTML omdat het in html format is gezet in Directus.

import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';

const Fetch = () => {
    const [Tasks, setTasks] = useState([]);

    useEffect(() => {
      fetch('https://fdnd-agency.directus.app/items/dropandheal_task')
        .then((res) => res.json())
        .then((data) => {
          console.log(data);
          setTasks(data.data);
        });
    }, []);

    return (
        <section>
            {Tasks.map((task) => (
                <article key={task.id}>
                    <h3>{task.title}</h3>
                    <p dangerouslySetInnerHTML={{ __html: task.description }} />
                    <Link to={`/task/${task.id}`}>View Details</Link> {/* Link to task detail page */} 
                </article>
            ))}
        </section>
    );
}

export default Fetch;

App.jsx

De App.jsx regelt de routing.

import './App.css';
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { Link } from 'react-router-dom';
import TaskDetail from './intro-task/taskDetail';

function App() {
  return (
      <div className="App">
        <h1>Drop & Heal</h1>
        <Link to="/task/1">Introductie Rouwtaken</Link>

        <Routes>
          <Route path="/task/:id" element={<TaskDetail />} /> 
        </Routes>
    </div>
  );
}

export default App;

TaskDetail.jsx

In de TaskDetail geef ik custom elementen mee aan de taken, dit doe ik door gebruik te maken van id === '2' &&. Hierdoor wordt gecheckt of de huidige id bij de huidige taak hoort en daarna worden de custom elementen gerendeerd als het true is. Elke taak staat op een aparte pagina.

import MeshgradBlue from '../components/Meshgrad-blue.jsx';
import MeshgradRed from '../components/Meshgrad-red.jsx';
import MeshgradGreen from '../components/Meshgrad-green.jsx';
import MeshgradPink from '../components/Meshgrad-pink';
import ArrowR from '../components/ArrowR.jsx';
import ArrowL from '../components/ArrowL.jsx';

import './task.css';

import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';

const TaskDetail = () => {
    const { id } = useParams();
    const [task, setTask] = useState(null);

    useEffect(() => {
        fetch(`https://fdnd-agency.directus.app/items/dropandheal_task/${id}`)
            .then((res) => res.json())
            .then((data) => {
                setTask(data.data); 
            });
    }, [id]);

    if (!task) {
        return <div>Loading...</div>; // Loading state aanpassen
    }

    return (
        <section>
            <h1>Introductie rouwtaken</h1>
            <h2>Rouwtaak</h2>
            <h3>{task.title}</h3>
            <div dangerouslySetInnerHTML={{ __html: task.description }} />

        {/* custom elements based on id */}
        {id === '1' && (
                <div className={`task-detail task-${id}`}>
                    <MeshgradBlue />
                    <Link to="/task/1"><ArrowL /></Link>
                    <Link to="/task/2"><ArrowR /></Link>

                    <div aria-busy="true" aria-describedby="progress-bar"></div>
                    <progress value="50" max="100"></progress>
                </div>
            )}

            {id === '2' && (
                <div className={`task-detail task-${id}`}>
                    <MeshgradRed />
                    <Link to="/task/1"><ArrowL /></Link>
                    <Link to="/task/3"><ArrowR /></Link>

                    <div aria-busy="true" aria-describedby="progress-bar"></div>
                    <progress value="60" max="100"></progress>
                </div>
            )}

            {id === '3' && (
                <div className={`task-detail task-${id}`}>
                    <MeshgradGreen />
                    <Link to="/task/2"><ArrowL /></Link>
                    <Link to="/task/4"><ArrowR /></Link>

                    <div aria-busy="true" aria-describedby="progress-bar"></div>
                    <progress value="70" max="100"></progress>
                </div>
            )}

            {id === '4' && (
                <div className={`task-detail task-${id}`}>
                    <MeshgradPink/>
                    <Link to="/task/3"><ArrowL /></Link>
                    <Link to="/task/4"><ArrowR /></Link>

                    <div aria-busy="true" aria-describedby="progress-bar"></div>
                    <progress value="80" max="100"></progress>
                </div>
            )}
        </section>
    );
};

export default TaskDetail;