Skip to content

Commit

Permalink
added async exercise and slightly reworked button styling
Browse files Browse the repository at this point in the history
  • Loading branch information
Kevin Lu committed Sep 20, 2024
1 parent 3111b77 commit d752227
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 11 deletions.
33 changes: 32 additions & 1 deletion pages/hack-school/js.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -547,4 +547,35 @@ findUser()
console.log("Age:", age + 5);
})
.catch((error) => console.error("Error:", error.message));
```
```

## Exercise 4: Async await practice

Create an async function fetchData that simulates an API call to fetch user data. The function should return a promise that resolves after 2 seconds with a user object containing name and email.

Then, write another async function displayUser that uses await to call fetchData and logs the user's information to the console.

<ToggleCodeBlock>
```javascript copy showLineNumbers
// Simulate API call using a Promise that resolves after 2 seconds
async function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ name: "John Doe", email: "[email protected]" });
}, 2000);
});
}

// Use async/await to fetch and display user data
async function displayUser() {
try {
const user = await fetchData();
console.log("User Name:", user.name);
console.log("User Email:", user.email);
} catch (error) {
console.error("Error:", error.message);
}
}
// Call the displayUser function displayUser();
```
</ToggleCodeBlock>
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
// to do: styling
import { useState, FC, ReactNode } from 'react';

import React, { useState } from 'react';

const ToggleCodeBlock = ({ children }) => {
const ToggleCodeBlock: FC<{ children: ReactNode }> = ({ children }) => {
const [isVisible, setIsVisible] = useState(false);

const toggleVisibility = () => {
setIsVisible(!isVisible);
};

return (
<div>
<button
type="button"
onClick={toggleVisibility}
onClick={() => setIsVisible(!isVisible)}
style={{
backgroundColor: 'blue',
backgroundColor: '#494D5F',
borderRadius: '4px',
padding: '0.5rem',
margin: '0.5rem',
}}
>
{isVisible ? 'Hide Code' : 'Show Code'}
Expand Down

0 comments on commit d752227

Please sign in to comment.