I have useEffect
which calls an action
from redux
to fetch uploads
useEffect(() => {
getUploads()
}, [getUploads])
However, I only want to fetch when the state changes, not fetch everytime the component renders. I have mapped the state like:
{filteredUploads.map((image, i) => { return (...) })}
I have tried to add getUploads
, filteredUploads
, filteredUploads.length
as dependency array. None of it worked.
My redux-action
:
export const getUploads = () => async dispatch => {
try {
dispatch({ type: 'LOADING', payload: true })
const res = await axios.get('/uploads/myuploads')
dispatch({
type: GETMYUPLOAD_SUCCESS,
payload: res.data
})
} catch (err) {
const error = err.response.data.error[0].msg
dispatch(setAlert(error, 'danger'))
}
}
mapStatetoProps
:
function mapStateToProps(state) {
const { myuploads, searchField } = state.useruploads;
return {
searchField: state.useruploads.searchField,
filteredUploads: myuploads.filter((upload) => upload.caption.toLowerCase().includes(searchField.toLowerCase()))
};
}