Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Redux store trigger a infinity rerender

I have this service class to get the data from backend. I’m making a get request to get some data in the getProjects method, i’m using axios:

export default class MissionService {

keycloak: KeycloakInstance
dispatch: AppDispatch
store

constructor(keycloak: KeycloakInstance){

this.store = useAppSelector((store) => store.xproj)
this.dispatch = useAppDispatch();
this.keycloak = keycloak;

}

async getProjects(){

if (!this.keycloak.token) return;

    backendAPI.defaults.headers.common[
      'Authorization'
    ] = `Bearer ${this.keycloak.token}`;


    await backendAPI
    .get('/mission/user')
    .then(({ data }) => {
      this.dispatch(setProjectList(data))
    })
    .catch((error) => errorNotification(error.response.data.message));
    
 }

After the data is recieve, it’s dispatch the data to the store. In my store i’m only saving the data, nothing more:

setProjectList: (state, action: PayloadAction<XProjProject[]>) => {

    state.projectsList = action.payload

},

I want to get this data when a specific component open:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const {

projectsList

} = useAppSelector((state) => state.xproj);

useEffect(() => { 

   missionService.getProjects()

}, [projectsList]);

But if i put the "projectList" inside the useEffect brackets, it’s trigger a infinite rerender. Everytime is making a request to the backend. I have to remove the "projectsList" from the brackets, but it’s not what i want because every time i create a new project, i want to update the components that using the "projectList" state.

Could anyone help with this, please? Thanks for any help.

>Solution :

Putting the projectsList in the brackets means that the useEffect will run again every time projectsList changes. Because the effect updates projectsList, running the effect will cause it to run again. projectsList should not be in those brackets.

You say that you want projectsList updated whenever you create a new project. I suggest doing that: update projectsList in a separate call when you do something like creating a new project.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading