Redux State is Repeated on Every GET Request

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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





Can you also post what would be the unique key for your photo object?
– Pritish Vaidya
Aug 10 at 21:49





Thanks, just posted it.
– Christian Lessard
Aug 10 at 22:01




1 Answer
1



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


photos



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];






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard