0

i'm working on my react blog project and i'm making a get request using an api using (redux-react) but my problem is that the function is been called continuously, instead it been called once
below is my code and image showing the continuous api call pls can anyone help out action file where i'm making d api call

export function fetchArticles(){
    return function(dispatch){
        const url  = `${baseUrl}/articles/list`
        return axios.get(url).then(res =>{
        console.log(res.data)
        dispatch( {type:articles.DISPLAY_ARTICLE, payload:res.data.data})
    })
    }
    
}

reducer file

function displayArticles (state=initialState, action){
    if(action.type===DISPLAY_ARTICLE){
        console.log(state)
        return Object.assign({}, state,{
            articles: state.articles.concat(action.payload)
        })
    }
    console.log(state)
    return state
}


function rootReducer(state=initialState, action){

    switch(action.type){
        case DISPLAY_ARTICLE:
            return displayArticles(state, action)
            break;

component file

function mapStateToProp (state){
    return {articles: state.articles}
}
const Index = (props)=>{
  useEffect(()=>{ 
    props.fetchArticles()

  }
  )

export default connect(
    (mapStateToProp),
    {fetchArticles}
)(Index)

enter image description here

Tosin Ayoola
  • 77
  • 1
  • 9

1 Answers1

0

It is because the way how you wrote your useEffect

useEffect(()=>{ 
  props.fetchArticles()
  // you did not pass any dependency array
} )

Since you did not pass any dependency array, function inside useEffect will get called in every rerender. with connect you are subscribed to the store. every time subscription detects a state change your component will rerender, since you did not pass the dependency array, the function inside useEffect will run which will fetch the data over and over again.

useEffect(()=>{ 
  props.fetchArticles()
  // empty dependency array means run only when initial mounting
},[] )
Yilmaz
  • 35,338
  • 10
  • 157
  • 202