Imagine the following situation: I have a registration flow in which some parts of this registration are saved in the session storage to be sent at the end of the flow for an API request. On one of these screens, I select some information and, to add the cards to this list of companies created, I open a modal component and save this information set in the modal in the session to retrieve it on the original screen and include it in the list. However, since this screen has already been loaded, the useeffect has no effect and if I pass the original list as a parameter, it enters an infinite loop.
How can I solve this?
Json example in principal screen:
novoJsonEmpresa = { ...jsonEmpresa, company: id, companyName: name, cards: [], // useeffect include session json here id: idCompany, };
UseEffect:
const [dataSourceListTESTE, setDataSourceListTESTE] = useState([]);
useEffect(() => {
let cartaoNovo = sessionStorage.getItem("jsonCartao");
if (cartaoNovo) {
cartaoNovo = JSON.parse(cartaoNovo);
setDataSourceListTESTE((prevList) =>
prevList.map((empresa) => {
if (empresa.id == cartaoNovo.id) {
return {
...empresa,
cartoes: [...empresa.cartoes, cartaoNovo],
};
}
return empresa;
})
);
}
console.log(dataSourceListTESTE);
}, [dataSourceListTESTE]); // when I pass this argument the list goes into infinite loop, if I don't pass any argument then this usage effect won't have any effect.
add button modal component:
const handleAdicionar = () => {
sessionStorage.setItem('jsonCartao', JSON.stringify(jsonCartao));
setIsModalOpen(false);
};
session json example:
{ "id":"1", "CartaoId":"example", "TipoCartao":"example", "NumeroCartao":"example" }
I need to include the json value that is taken from the session and set it in the cards field of the array within the list of objects that already exists on the main screen as soon as the modal closes, compared by the id as seen in the code, just once without entering a loop.