I have to make an api call that gets me a list.
So i am dispatching an action inside useEffect that makes an api call and then dispatches an action that is consumed by the reducer, which in turn returns updated state..
But the problem is when the component gets mounted useEffect is called infinitely..
I have tried-
1- Adding the dependencies inside the UseEffect
2- Passing empty array of dependencies..
This is my useEffect
useEffect(() => {
console.log(enteredSearch)
const identifier = setTimeout(() => {
console.log('sending request')
dispatch(getDSAList({
page: 1,
pageSize: 10,
searchString: enteredSearch
}))
}, 500);
return () => {
console.log('cleanup')
clearTimeout(identifier)
}
}, [enteredSearch])
This is the Action
export const getDSAList = (searchData) => {
return async (dispatch) => {
const fetchData = async () => {
console.log('Fetching Data')
const response = await webApiCall.post('https://a30fa91e-ae8b-42fb-8439-c2cc2d3cedfe.mock.pstmn.io/dsa/api/user/list',searchData)
if(response.data.status !== 200) {
throw new Error('Could not fetch DSA List')
}
return response.data.dsaResponse
}
try {
const dsaData = await fetchData()
dispatch(dsaActions.fetchDSAList(dsaData))
}
catch(error) {
console.log(error)
}
}
}
This is the Reducer
import { createSlice } from "@reduxjs/toolkit";
const dsaSlice = createSlice({
name: 'dsa',
initialState: {},
reducers: {
fetchDSAList(state, action) {
state.dsaList = action.payload.dsaList
},
commentAndStatusUpdate(state, action) {
state.commentAndStatusUpdate = action.payload
}
}
})
export const dsaActions = dsaSlice.actions
export default dsaSlice;
This is the store
import {configureStore} from '@reduxjs/toolkit'
import { loginSlice } from 'containers/signin/reducer'
import { logoutSlice } from 'containers/signout/reducer'
import dsaSlice from 'containers/DSA/reducer'
// Export store with reducers
export const store = configureStore({
preloadedState:{},
reducer: {
signin: loginSlice.reducer,
signout: logoutSlice.reducer,
dsa: dsaSlice.reducer
}
})
export const loginActions = loginSlice.actions
export const logoutActions = logoutSlice.actions