Home > Blockchain >  avoid function call when change page without changes in states in react
avoid function call when change page without changes in states in react

Time:07-12

i have this code:

import React, { useEffect, useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";
import useAuth from "../../hooks/useAuth";
import { getTopicsbyDcentro } from '../../slices/topicsSlice';
import CorpusNameCard from "./CorpusNameCard";
import { getAccessTokenApi } from "../../api/auth";
import { setToken } from "../../slices/userSlice";

const CorpusNameFit = () => {   
 
  const dispatch = useDispatch();
  const accessToken = getAccessTokenApi();  
  dispatch(setToken(accessToken));
    
  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.userTopics);   
  console.log(getTopics);
  const topics = Array.from(new Set(getTopics.map((topic)=> [topic.topicName, topic.workspace_id]))); 
  console.log(topics);
  const initFetch = useCallback(() => { 
    for (let dc of uniqueDCentros) {
      dispatch(getTopicsbyDcentro(dc));                   
    }
          
  }, [dispatch]);    
    
  useEffect(() => {
    console.log('useEffect');
    initFetch();  
  }, [user] ); 
  

  if (getTopics === undefined) return null;
  return (
    <div className="container" >
      <div className="subheader-bar">
        <h1 className="subheader-bar__title">Gestión del conocimiento</h1>
        <p className="subheader-bar__info">Estas son las temáticas que tienes asociadas a tu usuario. Selecciona la que quieras consultar.</p>
      </div>       
      <div className="row row-cols-1 justify-content-center row-cols-md-3 g-4 mt-5 mb-5">
        {topics && topics.map(title => <CorpusNameCard key={title} topic={title[0]} workspace_id={title[1]}/>)}        
      </div>
    </div>    
        
  );
};

export default CorpusNameFit;

When i click in navbar 'Corpus de Conocimiento' this code works. When i am in the next page if i click again in the navbar 'Corpus de Conocimiento', to comeback to choose other option, the code works again, and the screen show the items duplicates. Because in the slice i have a array.push to store some values.

This is the slice:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import TopicsService from '../services/topics.service';

const initialState = {
  userTopics: [],
  selectTopic: '',
 
};

export const getTopicsbyDcentro = createAsyncThunk (
  "topics/get",
  async (dcentroId) => {        
    const res = await TopicsService.getTopics(dcentroId); 
    return res.data;
  }
);

const topicsSlice = createSlice({
  name: 'topics',
  initialState, 
  reducers: {
    setTopic: (state, action) => {
      console.log(action.payload);      
      state.selectTopic = action.payload;
    }
    
  },
  extraReducers: {
    [getTopicsbyDcentro.fulfilled]: (state, action) => {
      //state.userTopics = initialState;
      state.userTopics.push(...action.payload);
    },        
  }});

export const { setTopic } = topicsSlice.actions;

const { reducer } = topicsSlice;
export default reducer;

The thing is, if i comeback, my array push and push and push, but if i refresh the page, start from the begining and only store the first call in the array.

I don't know if the issue is in the slice, that need check the data before push, or the usseffect that avoid recall the function if nothing has changed.

Thanks for your light

CodePudding user response:

A simple fix would be to check the store- if the values don't exist only then make the call (or dispatch action to set state/store)

  • Related