chciałabym aby ten komponent w pełni korzystał z kontekstu i nie używał dropsów pomóż mi go przerobić: import React, { type ChangeEvent, type FormEvent } from 'react';
import { Container, Form, Row, Col, Card, Spinner } from 'react-bootstrap';
import { useCalculationContext } from '../../contexts/calculationContext.tsx';
import type { ExtendedProfileState } from './types';
Oto refaktoryzowany komponent ProfileUser, który korzysta w pełni z kontekstu calculationContext i nie używa niepotrzebnych propsów (takich jak currencyOptions, currency, locale przekazanych jako propsy). Zakładam, że kontekst calculationContext dostarcza wszystkie niezbędne dane i funkcje.
jsx
User
mam taka pomocnicza funkcje: import { useEffect, useState } from 'react';
import type { CountryOption, RestCountry } from '../types/country.ts';
// Pomocnicza funkcja normalizująca locale, np. pl-pl → pl-PL
export const normalizeLocale = (locale: string): string => {
if (!locale) return 'pl-PL';
const parts = locale.replace('_', '-').split('-');
if (parts.length === 1) return parts[0].toLowerCase();
return parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
};
Teraz przeniesiemy logikę dotyczącą pobierania krajów, walut i ustawień lokalizacji bezpośrednio do Twojego CalculationContext. Wykorzystamy Twoją pomocniczą funkcję useFetchCountries i normalizeLocale.
Krok 1: Zmodyfikuj CalculationContextType
Dodajemy nowe pola, które będą przechowywać dane o krajach, walutach itd.:
typescript
type CalculationContextType = {
// ... Twoje istniejące pola ...
// Nowe pola dotyczące krajów i walut
loadingCountries: boolean;
countriesList: CountryOption[];
currencyOptions: string[];
countryToLocale: Record<string, string>;
currenciesMap: Record<string, string>;
userCountryCode?: string;
// Dodatkowo dodajemy funkcje pomocnicze
setUserCountryCode: (code: string) => void;
};
Krok 2: Przenieś useFetchCountries do CalculationProvider
Teraz wewnątrz CalculationProvider wywołamy useFetchCountries i dodamy jego wyniki do stanu kontekstu:
currencyOptions -> zastąpione przez currencies z kontekstu.
loadingCountries -> teraz pochodzi bezpośrednio z calculationContext.
countryToLocale -> nie było używane w komponencie, więc je usunąłem. Jeśli potrzebujesz tej mapy, dodaj ją do kontekstu i pobierz stamtąd.
Dodano pobieranie danych z kontekstu:
currencies - lista walut dostępna w kontekście.
loadingCountries - flaga informująca o ładowaniu listy krajów (jeśli ta logika jest zarządzana w kontekście).
countriesList - jeśli lista krajów jest już dostępna w kontekście, nie ma sensu dublować jej w propsach.
Domyślna wartość waluty:
W Form.Select dla waluty (Currency) użyłem state.currency || currency, co oznacza:
Jeśli użytkownik wybrał już walutę (state.currency nie jest puste), użyj tej wartości.
Jeśli nie, ustaw domyślnie walutę pobraną z kontekstu (currency).
Co musisz zrobić w calculationContext?
Upewnij się, że Twój kontekst (calculationContext) dostarcza następujące dane:
typescript
interface CalculationContextProps {
currency: string; // domyślna waluta
locale: string; // locale (jeśli potrzebne)
currencies: string[]; // lista dostępnych walut
loadingCountries: boolean; // czy kraje się ładują
countriesList: { cca2: string; name: string }[]; // lista krajów (jeśli jest zarządzana globalnie)
// inne potrzebne funkcje lub dane...
}
Jeśli countriesList jest zarządzany lokalnie w ProfileUser, to nie musisz nic zmieniać. Natomiast jeśli lista krajów pochodzi z API lub innego źródła globalnego, pobierz ją w kontekście i dostarczaj za pomocą useCalculationContext.
Przykładowe zmiany w kontekście (calculationContext.tsx):
};
plus moj kontekst wyglada tak pomóż mi przenieść ustawienia dotyczące kraju i currency do kontekstu import { createContext, useContext, useState } from 'react';
import type { GoalItem, GoalField } from '../components/goals/types';
import type { ExtendedProfileState } from '../components/profile-user/types.ts';
import type {GoalFieldErrors} from "../types/forms.ts";
// Identity
const [user, setUser] = useState('');
const [calcNumber, setCalcNumber] = useState('');
// Financial data
const [goals, setGoals] = useState<GoalItem[]>([]);
const [totalGoalsMonthly, setTotalGoalsMonthly] = useState(0);
const [totalIncomesMonthly, setTotalIncomesMonthly] = useState(0);
const [totalExpensesMonthly, setTotalExpensesMonthly] = useState(0);
// Currency and locale
const [currency, setCurrency] = useState('');
const [locale, setLocale] = useState('');
// Add a new empty goal row
const addRow = () => {
setGoals(prev => [
...prev,
{
id: crypto.randomUUID(),
goal: '',
year: '',
amount: '',
errors: {
name: '',
year: '',
amount: '',
},
},
]);
};
// Delete a goal by id
const deleteRow = (id: string) => {
setGoals(prev => prev.filter(goal => goal.id !== id));
};
// Update a specific field in a goal by id
const updateField = (id: string, field: GoalField, value: string | GoalFieldErrors) => {
setGoals(prevGoals =>
prevGoals.map(goal => {
if (goal.id !== id) return goal;
if (field === 'errors') {
return { ...goal, errors: value as GoalFieldErrors };
}
return { ...goal, [field]: value as string};
})
);
};
// Reset function
const resetCalculationData = () => {
setTotalGoalsMonthly(0);
setTotalIncomesMonthly(0);
setTotalExpensesMonthly(0);
setUser('');
setCalcNumber('');
setGoals([]);
// możesz też dodać reset innych stanów, jeśli chcesz
};
const value: CalculationContextType = {
state,
setState,
user,
setUser,
calcNumber,
setCalcNumber,
goals,
setGoals,
addRow,
deleteRow,
updateField,
totalGoalsMonthly,
setTotalGoalsMonthly,
totalIncomesMonthly,
setTotalIncomesMonthly,
totalExpensesMonthly,
setTotalExpensesMonthly,
currency,
locale,
setCurrency,
setLocale,
resetCalculationData,
};
return (
<CalculationContext.Provider value={value}>
{children}
</CalculationContext.Provider>
);
};
export const useCalculationContext = () => {
const context = useContext(CalculationContext);
if (!context) {
throw new Error('useCalculationContext must be used within a CalculationProvider');
}
return context;
};
import { normalizeLocale, useFetchCountries } from '../hooks/useFetchCountries'; // zaimportuj swoją funkcję
export const CalculationProvider = ({ children }: Props) => {
// ... Twoje istniejące stany ...
// Dodajemy stany dla krajów, walut itd.
const {
loading,
countries: countriesList,
currencyOptions,
countryToLocale,
currenciesMap,
userCountryCode,
} = useFetchCountries(normalizeLocale);
const [loadingCountries, setLoadingCountries] = useState(loading); // synchronizacja
const [userCountry, setUserCountry] = useState(userCountryCode); // synchronizacja
// Synchronizuj stany z hooka useFetchCountries
useEffect(() => {
setLoadingCountries(loading);
}, [loading]);
useEffect(() => {
setUserCountry(userCountryCode);
}, [userCountryCode]);
// Dodatkowa funkcja, aby można było ręcznie ustawić kraj użytkownika
const setUserCountryCode = (code: string) => {
setUserCountry(code);
};
// Teraz dodajemy wszystkie dane do `value` kontekstu
const value: CalculationContextType = {
// ... Twoje istniejące pola ...
// Nowe pola
loadingCountries,
countriesList,
currencyOptions,
countryToLocale,
currenciesMap,
userCountryCode: userCountry,
setUserCountryCode,
};
return (
<CalculationContext.Provider value={value}>
{children}
</CalculationContext.Provider>
);
};
Krok 3: Połącz dane krajów z profilem użytkownika (state)
W CalculationProvider mamy już state (profil użytkownika), który zawiera:
typescript
const [state, setState] = useState<ExtendedProfileState>({
name: '',
calcNumber: 0,
country: '',
currency: '',
errors: {},
countriesList: [], // 👈 to zostanie usunięte
currenciesMap: {}, // 👈 to zostanie usunięte
countryToLocale: {}, // 👈 to zostanie usunięte
currencyOptions: [], // 👈 to zostanie usunięte
});
Teraz nie potrzebujemy dublować danych w state. Usuń zbędne pola: