Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Happy Thoughts: Nella #97

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 2 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,13 @@

In this week's project, you'll be able to practice your React state skills by fetching and posting data to an API.

## Getting Started with the Project

### Dependency Installation & Startup Development Server

Once cloned, navigate to the project's root directory and this project uses npm (Node Package Manager) to manage its dependencies.

The command below is a combination of installing dependencies, opening up the project on VS Code and it will run a development server on your terminal.

```bash
npm i && code . && npm run dev
```

### The Problem

Describe how you approached to problem, and what tools and techniques you used to solve it. How did you plan? What technologies did you use? If you had more time, what would be next?
I have used useState and useEffect hooks to handle state and API fetching and posting. I'm also using components to handle different parts of the app, the form component for posting and the thoughts list for reading previous posts. I'm happy with how it turned out!

### View it live

Every project should be deployed somewhere. Be sure to include the link to the deployed project so that the viewer can click around and see what it's all about.
https://happii.netlify.app/

## Instructions

Expand Down
33 changes: 22 additions & 11 deletions index.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Happy Thought - Project - Week 7</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Happy Thought - Project</title>

<link rel="preload" href="https://fonts.googleapis.com/css2?family=Madimi+One&display=swap" as="style"
onload="this.rel='stylesheet'">
<noscript>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Madimi+One&display=swap">
</noscript>


</head>

<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx" defer></script>
</body>

</html>
8 changes: 7 additions & 1 deletion src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
import HappyThoughtsApp from "./components/HappyApp"



export const App = () => {
return <div>Find me in src/app.jsx!</div>;
return <>
<HappyThoughtsApp />
</>;
};
74 changes: 74 additions & 0 deletions src/components/Form.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { useState } from 'react';
import PropTypes from 'prop-types';

const MessageForm = ({ onThoughtAdded }) => {
const [message, setMessage] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false); // New loading state for form submission

const handleChange = (e) => {
setMessage(e.target.value);
setError('');
};

const handleSubmit = async (e) => {
e.preventDefault();
if (message.length < 1 || message.length > 140) {
setError('Message must be between 1 and 140 characters long.');
return;
}

setLoading(true);

try {
const response = await fetch('https://happy-thoughts-ux7hkzgmwa-uc.a.run.app/thoughts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message }),
});

if (!response.ok) {
throw new Error('Failed to post the thought');
}

const data = await response.json();
setMessage('');
onThoughtAdded(data);
} catch (err) {
setError('An error occurred while posting the thought.');
console.error(err);
} finally {
setLoading(false);
}
};

return (
<form onSubmit={handleSubmit}>
<label>
What&apos;s making you happy right now?
<textarea
value={message}
onChange={handleChange}
rows="4"
placeholder=":)"
style={{ resize: 'none' }}
/>
</label>
{error && <p style={{ color: 'red' }}>{error}</p>}
<p className="counter" style={{ color: message.length > 140 ? 'red' : 'black' }}>
{message.length}/140
</p>
<button className="post-button" type="submit" disabled={loading}> {/* Disable button while loading */}
{loading ? 'Sending...' : 'Send Happy Thought'}
</button>
</form>
);
};

MessageForm.propTypes = {
onThoughtAdded: PropTypes.func.isRequired,
};

export default MessageForm;
59 changes: 59 additions & 0 deletions src/components/HappyApp.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { useState, useEffect } from 'react';
import ThoughtsList from "./HappyT";
import MessageForm from "./Form";

const HappyThoughtsApp = () => {
const [thoughts, setThoughts] = useState([]);
const [loading, setLoading] = useState(true); // Initialize loading state

useEffect(() => {
const fetchThoughts = async () => {
try {
const response = await fetch('https://happy-thoughts-ux7hkzgmwa-uc.a.run.app/thoughts');
if (!response.ok) {
throw new Error('Failed to fetch thoughts');
}
const data = await response.json();
setThoughts(data);
} catch (err) {
console.error('Error fetching thoughts:', err);
} finally {
setLoading(false); // Set loading to false when done
}
};

fetchThoughts();
}, []);

const addThought = (newThought) => {
setThoughts([newThought, ...thoughts]);
};

const onThoughtLiked = (thoughtId) => {
setThoughts((prevThoughts) =>
prevThoughts.map((thought) =>
thought._id === thoughtId ? { ...thought, hearts: thought.hearts + 1 } : thought
)
);
};

return (
<>
<header><h1>Happy Thoughts Feed 😊</h1></header>
<main>
<section className="form-box">
<MessageForm onThoughtAdded={addThought} />
</section>
<section className="thoughts-feed">
{loading ? (
<p>Loading thoughts...</p>
) : (
<ThoughtsList thoughts={thoughts} onThoughtLiked={onThoughtLiked} />
)}
</section>
</main>
</>
);
};

export default HappyThoughtsApp;
68 changes: 68 additions & 0 deletions src/components/HappyT.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import PropTypes from 'prop-types';

const ThoughtsList = ({ thoughts, onThoughtLiked }) => {
const handleLike = async (thoughtId) => {
try {
const response = await fetch(`https://happy-thoughts-ux7hkzgmwa-uc.a.run.app/thoughts/${thoughtId}/like`, {
method: 'POST',
});
if (response.ok) {
onThoughtLiked(thoughtId);
} else {
console.error('Failed to like the thought');
}
} catch (error) {
console.error('Error liking the thought:', error);
}
};

const formatTimeAgo = (createdAt) => {
const now = new Date();
const postDate = new Date(createdAt);
const diffInMs = now - postDate;
const diffInMinutes = Math.floor(diffInMs / (1000 * 60));
const diffInHours = Math.floor(diffInMs / (1000 * 60 * 60));
const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24));

if (diffInMinutes < 60) {
return `${diffInMinutes} minute${diffInMinutes !== 1 ? 's' : ''} ago`;
} else if (diffInHours < 24) {
return `${diffInHours} hour${diffInHours !== 1 ? 's' : ''} ago`;
} else {
return `${diffInDays} day${diffInDays !== 1 ? 's' : ''} ago`;
}
};

return (
<>
<ul>
{thoughts.map((thought) => (
<li key={thought._id}>
<p className="thought-p">{thought.message}</p>
<div className="heart-time-div">
<div className="heart-info">
<button className="heart-button" onClick={() => handleLike(thought._id)}>❤️</button>
<p> x {thought.hearts}</p>
</div>
<p className="posted-time">{formatTimeAgo(thought.createdAt)}</p>
</div>
</li>
))}
</ul>
</>
);
};

ThoughtsList.propTypes = {
thoughts: PropTypes.arrayOf(
PropTypes.shape({
_id: PropTypes.string.isRequired,
message: PropTypes.string.isRequired,
hearts: PropTypes.number.isRequired,
createdAt: PropTypes.string.isRequired,
})
).isRequired,
onThoughtLiked: PropTypes.func.isRequired,
};

export default ThoughtsList;
Loading