Reputation: 17
I have in my app a React component named Jornal. It is a list of documents. And I have about 30 types of jornals. In NodeJS I make interface description of each jornal. So jornals are typed by TS.
But how I can use type info to work with data from backend on the frontend?
On the frontend in the Jornal component, I use custom hook to get data from backend. After the data is received, it's saved to the React state of jornal component. And ones data received jornal component render list. Each row of the list is separate component depended on type of jornal.
So how I can use TS interface in custom hook which receive data from backend? how I can make jornal react state typed?
Thanks
Upvotes: 0
Views: 63
Reputation: 21
Custom Hook: Use a generic type to make the hook reusable for all journal types. Some as below
function useFetchJornalData<T>(endpoint: string): { data: T | null; loading: boolean; error: string | null } {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(endpoint);
const jsonData: T = await response.json();
setData(jsonData);
} catch (err) {
setError("Error fetching data");
} finally {
setLoading(false);
}
}
fetchData();
}, [endpoint]);
return { data, loading, error };
}
Typed State: Type the state in the Jornal component using the journal type or its union type.
type JornalData = JornalTypeA | JornalTypeB;
Typed Rows: Use type guards (like "title" in data) to differentiate between journal types in the JornalRow component.
Upvotes: 1