Skip to content

Commit

Permalink
Add useEffect and useContext to fetch and update goals
Browse files Browse the repository at this point in the history
  • Loading branch information
DiegoT4l committed Feb 14, 2024
1 parent 4905f4e commit 27af5ab
Show file tree
Hide file tree
Showing 6 changed files with 134 additions and 45 deletions.
10 changes: 10 additions & 0 deletions public/goal.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"id": 2,
"details": "Backend",
"frequency": 1,
"period": "día",
"icon": "📚",
"finish": 52,
"limitDate": "2030-12-31",
"completed": 5
}
52 changes: 52 additions & 0 deletions public/goals.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
[
{
"id": 1,
"details": "Correr por 30 minutos",
"frequency": 1,
"period": "día",
"icon": "🏃‍♂️",
"finish": 52,
"limitDate": "2030-12-31",
"completed": 5
},
{
"id": 2,
"details": "Leer 30 minutos",
"frequency": 1,
"period": "día",
"icon": "📚",
"finish": 52,
"limitDate": "2030-12-31",
"completed": 5
},
{
"id": 3,
"details": "Hacer 30 minutos de meditación",
"frequency": 1,
"period": "día",
"icon": "🧘‍♂️",
"finish": 52,
"limitDate": "2030-12-31",
"completed": 5
},
{
"id": 4,
"details": "Hacer 30 minutos de ejercicio",
"frequency": 1,
"period": "día",
"icon": "🏋️‍♂️",
"finish": 52,
"limitDate": "2030-12-31",
"completed": 5
},
{
"id": 5,
"details": "Hacer 30 minutos de yoga",
"frequency": 1,
"period": "día",
"icon": "🧘‍♂️",
"finish": 52,
"limitDate": "2030-12-31",
"completed": 5
}
]
19 changes: 19 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { useEffect, useContext } from 'react';
import { Context } from './services/Memory';
import { requestGoals } from './services/Requests';
import './App.css';
import Layout from "./components/Shared/Layout";
import {Route, Routes} from "react-router-dom";
Expand All @@ -7,6 +10,22 @@ import NotFound from "./components/Shared/NotFound";
import Modal from "./components/Shared/Modal";

function App() {

const [, dispatch] = useContext(Context);

useEffect(() => {
const fetchData = async () => {
try {
const goals = await requestGoals(); // Espera la respuesta
dispatch({ type: 'LOAD_GOALS', goals });
} catch (error) {
console.error("Error fetching goals:", error);
}
};

fetchData(); // Llama a la función asíncrona
}, []);

return (
<Routes>
<Route path='/' element={<Layout />}>
Expand Down
28 changes: 16 additions & 12 deletions src/components/new/Details.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import styles from './Details.module.css';
import {useContext, useEffect, useState} from 'react';
import {Context} from "../../services/Memory";
import {useNavigate, useParams} from "react-router-dom";
import {createGoal, deleteGoal, updateGoal} from "../../services/Requests";


function Details() {

const {id} = useParams();
const {id} = useParams(); // <--- Obtiene el id de la url si existe

const [form, setForm] = useState({
details: '',
Expand All @@ -28,7 +29,7 @@ function Details() {
completed
} = form;

const [state, dispatch] = useContext(Context);
const [state, dispatch] = useContext(Context); // <--- Obtiene el estado global y el dispatch del contexto

const onChange = (e, prop) => {
setForm(prevEstate => ({
Expand All @@ -38,7 +39,7 @@ function Details() {
}

const navigate = useNavigate();
const goalMemory = state.objects[id];
const goalMemory = state.objects[id]; // <--- Obtiene el objeto de la memoria

useEffect(() => {
if (!id) return;
Expand All @@ -48,18 +49,21 @@ function Details() {
setForm(goalMemory);
}, [id, goalMemory, navigate]);

const createGoal = () => {
dispatch({ type : 'CREATE_GOAL', goal: form });
const create = async () => {
const newGoal = await createGoal();
dispatch({ type : 'CREATE_GOAL', goal: newGoal });
navigate('/list');
}

const updateGoal = () => {
dispatch({ type : 'UPDATE_GOAL', goal: form });
const update = async () => {
const updatedGoal = await updateGoal();
dispatch({ type : 'UPDATE_GOAL', goal: updatedGoal });
navigate('/list');
}

const deleteGoal = () => {
dispatch({ type : 'DELETE_GOAL', goal: form });
const deleteG = async () => {
const idDeleted = await deleteGoal();
dispatch({ type : 'DELETE_GOAL', goal: idDeleted });
navigate('/list');
}

Expand Down Expand Up @@ -147,17 +151,17 @@ function Details() {
<div className={styles.buttons}>
{!id && <button
className='button button--black'
onClick={createGoal}
onClick={create}
>Guardar
</button>}
{id && <button
className='button button--black'
onClick={updateGoal}
onClick={update}
>Actualizar
</button>}
{id && <button
className='button button--red'
onClick={deleteGoal}
onClick={deleteG}
>Borrar
</button>}
<button
Expand Down
38 changes: 5 additions & 33 deletions src/services/Memory.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,26 @@
import {createContext, useReducer} from "react";


const memory = localStorage.getItem('goals');
const InitialState = memory ?
JSON.parse(memory) :
{
const InitialState = {
orderList: [],
objects: {},
}

const reducer = (state, action) => {
switch (action.type) {
case 'LOAD_GOALS': {
const goals = action.goal || []; // <--- Si no hay goals, se crea un array vacío.
const goals = action.goals;
const newState = {
orderList: goals.map((goal) => goal.id),
orderList: goals.map(goal => goal.id),
objects: goals.reduce((obj, goal) => {
obj[goal.id] = goal;
return obj;
}, {})
}
localStorage.setItem('goals', JSON.stringify(newState));
return newState;
}
case 'CREATE_GOAL': {

function generateId(min, max) {
const numbers = [];
for (let i = min; i <= max; i++) {
numbers.push(i);
} // <--- Array con números del 1 al 100000

// Algoritmo de Fisher-Yates para desordenar el array.
for (let i = numbers.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[numbers[i], numbers[j]] = [numbers[j], numbers[i]];
}

return numbers[0]; // <--- Devuelve un número aleatorio del 1 al 100000
}

const id = generateId(1, 100000);
const id = action.goal.id;
const newState = {
orderList: [...state.orderList, id],
objects: {
Expand All @@ -51,7 +31,6 @@ const reducer = (state, action) => {
}
}
}
localStorage.setItem('goals', JSON.stringify(newState));
return newState;
}
case 'UPDATE_GOAL': {
Expand All @@ -61,30 +40,23 @@ const reducer = (state, action) => {
...action.goal
}
const newState = { ...state };
localStorage.setItem('goals', JSON.stringify(newState));
return newState;
}
case 'DELETE_GOAL': {
const id = action.goal.id;
const id = action.goal;
const newOrder = state.orderList.filter((goalId) => goalId !== id);
delete state.objects[id];
const newState = {
orderList: newOrder,
objects: { ...state.objects }
}
localStorage.setItem('goals', JSON.stringify(newState));
return newState;
}
default:
throw new Error('Action not found');
}
}

// reducer(InitialState, {
// type: 'LOAD_GOALS',
// goals: goalsMock
// });

export const Context = createContext(null);

function Memory({ children }) {
Expand Down
32 changes: 32 additions & 0 deletions src/services/Requests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export async function requestGoals() {
const response = await fetch('/goals.json');
const goals = await response.json();
return goals;
}

export async function requestGoal() {
const response = await fetch('/goal.json');
const goal = await response.json();
return goal;
}

export async function createGoal() {
const response = await fetch('/goal.json');
const newGoal = await response.json();
console.log('Meta creada: ',newGoal);
return newGoal;
}

export async function updateGoal(goal) {
const response = await fetch('/goal.json');
const updatedGoal = await response.json();
console.log('Meta actualizada: ',updatedGoal);
return updatedGoal;
}

export async function deleteGoal() {
const response = await fetch('/goal.json');
const deletedGoal = await response.json();
console.log('Meta eliminada: ',deletedGoal.id);
return deletedGoal.id;
}

0 comments on commit 27af5ab

Please sign in to comment.