I don't know why but when my provider is updated, he is not update in my component function.
interface CompanyContextType {
company: EntrepriseReceiveInterface | null;
setCompany: React.Dispatch<
React.SetStateAction<EntrepriseReceiveInterface | null>
>;
}
const CompanyContext = createContext<CompanyContextType | undefined>(undefined);
export const useCompany = () => {
const context = useContext(CompanyContext);
if (!context) {
throw new Error("useCompany must be used within a CompanyProvider");
}
return context;
};
interface CompanyProviderProps {
children: ReactNode;
}
export const CompanyProvider: React.FC<CompanyProviderProps> = ({
children,
}) => {
const { companyId } = useParams();
const [company, setCompany] = useState<EntrepriseReceiveInterface | null>(
null
);
const [loading, setLoading] = useState<boolean>(true);
if (!companyId) {
return <h1>Erreur</h1>;
}
const getCompanyUnique = EntrepriseGetByIdUseCase(companyId);
useEffect(() => {
if (getCompanyUnique.status === "success") {
const body = getCompanyUnique.data.body;
console.log("body", body);
setCompany(body);
console.log("company", company);
setLoading(false);
}
}, [getCompanyUnique.status, companyId]);
return (
<CompanyContext.Provider value={{ company, setCompany }}>
{loading ? <div>Chargement...</div> : children}
</CompanyContext.Provider>
);
};
Here is my provider, for a dashboard with multiple clients and when you change client, you change the dashboard. The second console.log isn't updated.
const { company, setCompany } = useCompany();
if (!company) {
return <h1>Erreur</h1>;
}
const { mutate: setColorMutation } = useEditCompanyColor();
console.log("company", company._id);
const handlePickerChange = (color: any, currentCompany: any) => {
console.log(currentCompany._id);
setColorMutation(
{ entrepriseId: currentCompany._id, color: color.hex },
{
onSuccess: () => {
setCompany((prevCompany) =>
prevCompany ? { ...prevCompany, colorPrimary: color.hex } : null
);
toast.success("Vous avez bien changé la couleur primaire", {
style: { borderColor: "var(--successHexa)" },
});
},
onError: () => {
toast.error("Une erreur est survenue, veuillez réessayer", {
style: { borderColor: "var(--errorHexa)" },
});
},
}
);
};
return (
<Card className="flex justify-between items-center h-full">
<CardHeader>
<CardTitle>Couleur - Entreprise</CardTitle>
<CardDescription>Choisissez votre couleur d'entreprise</CardDescription>
</CardHeader>
<CardContent className="flex flex-col xl:flex-row p-0 pt-2 pb-2 pr-6 xl:pt-0 xl:pb-0 items-center space-x-2">
<div
className={"text-2xl font-bold rounded-full w-16 h-16"}
style={{ backgroundColor: company.colorPrimary }}
></div>
{company._id}
<Compact
color={company.colorPrimary}
onChange={(color) => handlePickerChange(color, company)}
/>
</CardContent>
</Card>
);
The problem for me is the function, {company._id} show the good id all the time but in the function is all the time the same company idk why :/
I try useCallback, I try useEffect to update