I have this code to try to create and array of values to use then in a map to print the value names in cards (bootstrap).
const { user } = useAuth();
const {
responsable,
editor,
} = user;
const uniqueDCentros = Array.from(new
Set(JSON.parse(responsable).concat(JSON.parse(editor))));
const getTopics = useSelector((state)=> state.topics); // i received from reducer
//the **topics** everytime that the **initFetch** execute the loop that is inside.
const [uniqueTopics, setUniqueTopics] = useState([])
let resTopics = [];
for(let topic of getTopics) {
resTopics.push(topic.topicName)
}
const dispatch = useDispatch();
const initFetch = useCallback(() => {
for (let dc of uniqueDCentros) {
dispatch(getTopicsbyDcentro(dc)); // get the 'topics' for every 'dc' that i want to use together,
}
}, dispatch);
useEffect(() => {
initFetch();
setUniquetopics([restTopics, ...uniqueTopics])
}, initFetch);
I would like to store all the topics to use later. I tryed with push inside the loop, and with useState() to store the values, but not works.
Some help for me. Thanks
It looks like you already have topics on state in redux. Therefore you don't need to copy that state into this component. You can simply access it like
const topics = getTopics.map(t => t.topicName);
Edit: it would be easiest to keep all the results on redux, but in case you don't want to do that for some reason, keep track of each element that the component reacts to.
const useAccumulate = (list) => {
const [acc, setAcc] = useState([]);
useEffect(() => {
// Every time the reference for the list updates
// add every element into the accumulator
setAcc(a => [...a, ...list]);
}, [list]);
return acc;
}