Compare commits

...

3 Commits

Author SHA1 Message Date
e560248
dbfc23068c custom hook useLocalStorage 2025-04-07 16:28:29 +02:00
e560248
42d87e5275 custom Hook useMediaQuery 2025-04-07 15:57:46 +02:00
e560248
3a4be8d359 add performance calc 2025-04-07 15:38:36 +02:00
5 changed files with 97 additions and 3 deletions

View File

@@ -1,16 +1,30 @@
import { FormEvent, useRef, useState } from "react"; import { FormEvent, useRef, useState } from "react";
import useLocalStorage from "../../../hooks/useLocalStorage";
interface FormValues {
email: string;
password: string;
}
export default function RefExercise(): React.ReactElement { export default function RefExercise(): React.ReactElement {
console.log("RefExercise rendered"); console.log("RefExercise rendered");
const emailRef = useRef<HTMLInputElement>(null); const emailRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null); const passwordRef = useRef<HTMLInputElement>(null);
const {setStoredValue, value: formDataValues} = useLocalStorage<FormValues>("formdata", {
email: "",
password: ""
} );
const handleSubmit = () => { const handleSubmit = () => {
console.log("submit", { console.log("submit", {
email: emailRef.current?.value, email: emailRef.current?.value,
password: passwordRef.current?.value password: passwordRef.current?.value
}); });
setStoredValue({
email: emailRef.current?.value || "",
password: passwordRef.current?.value || ""
});
passwordRef.current?.focus(); passwordRef.current?.focus();
} }
@@ -47,8 +61,8 @@ export default function RefExercise(): React.ReactElement {
<div style={{ display: "flex", flexDirection: "column", gap: "3rem" }}> <div style={{ display: "flex", flexDirection: "column", gap: "3rem" }}>
<div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}> <div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
<h3>values by ref</h3> <h3>values by ref</h3>
<input type="text" placeholder="email" ref={emailRef}/> <input type="text" placeholder="email" ref={emailRef} defaultValue={formDataValues?.email}/>
<input type="text" placeholder="password" ref={passwordRef}/> <input type="text" placeholder="password" ref={passwordRef} defaultValue={formDataValues?.password}/>
<button onClick={handleSubmit}>Submit</button> <button onClick={handleSubmit}>Submit</button>
</div> </div>
<div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}> <div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>

View File

@@ -19,6 +19,8 @@ export default function UserEffect() {
return; return;
} }
const start = performance.now(); // Start measuring performance
setLoading(true); setLoading(true);
// Using AbortController to cancel the fetch request if the component unmounts // Using AbortController to cancel the fetch request if the component unmounts
@@ -33,6 +35,9 @@ export default function UserEffect() {
return response.json(); return response.json();
}).then(data => { }).then(data => {
setUser(data); setUser(data);
const end = performance.now(); // End measuring performance
const timeTaken = end - start; // Calculate the time taken
console.log(`Fetch completed in ${Math.round(timeTaken)} milliseconds`);
setLoading(false); setLoading(false);
}).catch(error => { }).catch(error => {
console.error("There was a problem with the fetch operation:", error); console.error("There was a problem with the fetch operation:", error);

View File

@@ -1,8 +1,13 @@
import { useFetch } from "../../hooks/useFetch"; import { useFetch } from "../../hooks/useFetch";
import { useMediaQuery } from "../../hooks/useMediaQuery";
export function UserOverview() { export function UserOverview() {
const {data, loading, error} = useFetch("https://jsonplaceholder.typicode.com/users"); const {data, loading, error} = useFetch("https://jsonplaceholder.typicode.com/users");
const isMobile = useMediaQuery('(max-width: 600px)');
console.log("isMobile", isMobile);
if (error) { if (error) {
return <p>Error: {error}</p>; return <p>Error: {error}</p>;
} }
@@ -18,7 +23,7 @@ export function UserOverview() {
<ul> <ul>
{data.map((user: { id: number; name: string; email: string; website: string }) => ( {data.map((user: { id: number; name: string; email: string; website: string }) => (
<li key={user.id}> <li key={user.id}>
<strong>{user.name}</strong> ({user.email}) - {user.website} <strong>{user.name}</strong> <div style={{display: isMobile ? 'none' : 'block' }}>({user.email}) - {user.website}</div>
</li> </li>
))} ))}
</ul> </ul>

View File

@@ -0,0 +1,39 @@
import { useState } from "react";
export default function useLocalStorage<T>(key: string, initialValue: T | null) {
const [value, setValue] = useState<T | null>(() => {
try {
if (typeof window === "undefined") {
return initialValue;
}
const storedValue = localStorage.getItem(key);
return storedValue ? JSON.parse(storedValue) : initialValue;
} catch (error) {
console.error("Error reading from localStorage", error);
return initialValue;
}
});
const setStoredValue = (newValue: T) => {
try {
const valueToStore = newValue instanceof Function ? newValue(value) : newValue;
setValue(valueToStore);
if (typeof window !== "undefined") {
localStorage.setItem(key, JSON.stringify(valueToStore));
}
} catch (error) {
console.error("Error writing to localStorage", error);
}
}
const removeStoredValue = () => {
try {
if (typeof window !== "undefined") {
localStorage.removeItem(key);
}
setValue(null);
} catch (error) {
console.error("Error removing from localStorage", error);
}
}
return {value, setStoredValue, removeStoredValue};
}

View File

@@ -0,0 +1,31 @@
import { useEffect, useState } from "react";
/**
* Custom hook to check if a media query matches the current viewport.
* @param query - The media query string (e.g., '(max-width: 600px)')
* @returns A boolean indicating whether the media query matches.
*/
export function useMediaQuery(query: string) {
const [matches, setMatches] = useState<boolean>(false);
useEffect(() => {
const mediaQueryList = window.matchMedia(query);
const handleChange = (event: MediaQueryListEvent) => {
setMatches(event.matches);
};
// Set the initial value
setMatches(mediaQueryList.matches);
// Add event listener
mediaQueryList.addEventListener('change', handleChange);
// Cleanup function to remove the event listener
return () => {
mediaQueryList.removeEventListener('change', handleChange);
};
}, [query]);
return matches;
}