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:
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.