Christian Lessard
Christian Lessard

Reputation: 425

Redux State is Repeated on Every GET Request

I am mapping through an array where I am taking every item in the array and calling a GET request on each item. Then I am pushing them all together in my redux state. The issue is that every time I reload the information is repeated. I am thinking that the way to solve this issue is to clean out my redux store everytime that the request is run however, I do not want to wipe everything, just the photos portion in this case.

momentcontent.js:

 componentDidMount () {

      this.props.photos.map(photo => {
        this.props.fetchPhoto(this.props.token, photo)}
      )
    }

index.js (actions):

export const fetchPhoto = (token, photo) => dispatch => {
  console.log('right token')
  console.log(token);
  fetch(photo, {
    method: 'GET',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': `Token ${token}`,
    }
  })
  .then(res => res.json())
  .then(parsedRes => {
    console.log('photo data')
    console.log(parsedRes)
    dispatch(getPhoto(parsedRes))
  })
}

export const getPhoto = (photo) => {
  console.log('RES')
  console.log(photo)
  return {
    type: GET_PHOTO,
    photo: photo
  }
}

photo.js:

import {
  GET_PHOTO
} from '../actions';

const initialState = {
  photo: []
}

const photoReducer = (state = initialState, action) => {
  switch(action.type) {
    case GET_PHOTO:
      return {
        ...state,
        photo: [...state.photo, action.photo]
      }

    default:
      return state;
  }
}

export default photoReducer

my console (I should have 9 items in the array, I have 27 here):

enter image description here

Upvotes: 2

Views: 469

Answers (1)

Pritish Vaidya
Pritish Vaidya

Reputation: 22209

Rather than clearing the redux store photos object and re-adding, you can check if the photo already exists in the store or not.

Assuming that your state contains a photo array, action contains photo object and photo (the image url instance) is a unique object

Therefore you can modify your reducer as

case GET_PHOTO:
 return state.photo.some(( { photo } ) => photo === action.photo.photo)
         ? state
         : [...state.photo, action.photo];

Upvotes: 1

Related Questions