Action not updating reducer when invoked - reactjs

I cannot get my reducer to update. I can step into the action when I fire this.completeQuiz(id) in my debugger but my state doesn't get updated. Any ideas?
import {
submitAnswer,
resetQuiz,
nextQuestion,
completeQuiz
} from "../actions/videos";
class TestYourselfScreen extends React.Component {
constructor(props) {
super(props);
this.onCapture = this.onCapture.bind(this);
}
completeQuiz = id => {
let video = this.props.videos.find(obj => obj.id == id);
let correctAnswers = video.results.correctAnswers;
const questionsFiltered = video.questions.filter(obj => obj.question != "");
completeQuiz({
id,
totalScore: correctAnswers.length / questionsFiltered.length
});
};
render() {
.....
return (
{questionsFiltered.length > 0 && !completed && (
<View
style={{
flex: 1
}}
>
....
<Button
title={lastQuestion ? "Finish" : "Next"}
buttonStyle={[styles.button]}
disabled={
!results.correctAnswers.includes(current) &&
!results.incorrectAnswers.includes(current)
? true
: false
}
onPress={() =>
lastQuestion ? this.completeQuiz(id) : this.next(id, current)
}
/>
</View>
)}
{completed === true && (
<View
style={{
flex: 1
}}
>
<ViewShot ref="viewShot" options={{ format: "jpg", quality: 0.9 }}>
...
</View>
)}
</ScrollView>
);
}
}
const mapStateToProps = state => {
return {
videos: state.tcApp.videos
};
};
const mapDispatchToProps = dispatch => ({
submitAnswer: data => dispatch(submitAnswer(data)),
resetQuiz: id => dispatch(resetQuiz(id)),
nextQuestion: data => dispatch(nextQuestion(data)),
completeQuiz: data => dispatch(completeQuiz(data))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(TestYourselfScreen);
Action:
export const completeQuiz = data => ({
type: "COMPLETE",
data
});
Reducer:
import { trimText } from "../helpers";
export function tcApp(
state = { videos: [], search: { videos: [], term: "" } },
action
) {
switch (action.type) {
....
case "COMPLETE": {
const { completed, totalScore, id } = action.data;
return {
videos: state.videos.map(video =>
video.id === id
? {
...video,
results: {
totalScore
},
completed: true
}
: video
),
search: { term: "", videos: [] }
};
}
default:
return state;
}
}

I think your action is available through props do it as this
completeQuiz = id => {
let video = this.props.videos.find(obj => obj.id == id);
let correctAnswers = video.results.correctAnswers;
const questionsFiltered = video.questions.filter(obj => obj.question != "");
this.props.completeQuiz({
id,
totalScore: correctAnswers.length / questionsFiltered.length
});
};
because we mapDispatchToProps
Hope it helps

Related

Redux store is being updated but the component is not re-rendering

I have following reducer:
const INITIAL_STATE = {
wallets: [],
selectedAccount: null,
selectedNetwork:null
};
export const setActive = (id, payload) => ({
type: actionTypes.SET_ACTIVE,
id,
payload,
});
const editItem = wallets.map(item => (item.id !== action.id ? {
...item, active: false } : { ...item, active: true }));
case actionTypes.SET_ACTIVE:
return {
...state,
accounts: [...state.wallets,editItem],
selectedAccount: action.payload,
};
I console.logged everything and store is being updated but the problem is my component is not re-rendering for some reason.
setActiveFunc = item => {
const { actions } = this.props;
const selectedAcc = {
name: item.name,
address: item.address,
active: item.active,
id: item.id,
};
actions.setActive(item.id, selectedAcc);
};
const UserMenuAccount = ({ active, account, balance }) => (
<View style={styles.accountContainer}>
<Image
source={require('../../../assets/Usermenu/check.png')}
style={[styles.icon, { opacity: active ? 1 : 0 }]}
/>
<Text style={styles.text}>{account}</Text>
<Text style={[styles.text, { opacity: 0.5 }]}>
{balance}
{' '}
ETH
</Text>
</View>
);
class UserMenuAccounts extends Component {
setActiveFunc = item => {
const { actions } = this.props;
const selectedAcc = {
name: item.name,
address: item.address,
active: item.active,
id: item.id,
};
actions.setActive(item.id, selectedAcc);
};
render() {
const { GetWallets } = this.props;
return (
<View>
{GetWallets.map(users => (
<TouchableOpacity
onPress={() => {
this.setActiveFunc(users);
}}
key={users.id}
>
<UserMenuAccount
account={`${users.name}`}
balance={0}
active={users.active}
key={users.id}
/>
</TouchableOpacity>
))}
</View>
);
}
}
The function shall create checked icon once active=true and even tho reducer is doing its thing the icon is not appearing
This is the function I'm using in the component, any suggestions?
You forgot to add the 'accounts' in the initial state of your reducer:
const INITIAL_STATE = {
wallets: [],
accounts: [],
selectedAccount: null,
selectedNetwork:null
};
accounts: [...state.wallets,editItem],
should rather be
accounts: state.wallets.map(item => (item.id !== action.id ? { ...item, active: false } : { ...item, active: true }));
see map will create a new array above you were spreading an array and inserting another inside it

React native updating every 6th state automatically

Whenever I press the heart button it updates the state and calls renderHeart method in TutorsCard.js but it also updates every 6th card's state and so on when I scroll down to fetch more profiles so they appear to be liked as well. It might be an issue of shouldComponentUpdate in TutorsCard.js I change shouldComponentUpdate multiple times but it didn't work.
Feed.js
class Feed extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
profiles: new DataProvider((r1, r2) => {
return r1 !== r2;
}),
loading: false,
liked: false,
color: 'red',
refreshing: false,
limit: 10
};
this.layoutProvider = new LayoutProvider((i) => 0, (type, dim) => {
dim.width = width;
dim.height = 250;
})
}
onRefresh = () => {
this.getProfiles();
}
shouldComponentUpdate(nextProps, nextState) {
if (JSON.stringify(this.props) === JSON.stringify(nextProps) &&
this.state === nextState) {
console.log("should cmp update feed false")
return false
}
if (JSON.stringify(this.props) !== JSON.stringify(nextProps) ||
this.state !== nextState) {
console.log("should cmp update feed true")
return true
}
}
onEndReach = async () => {
this.setState({ limit: this.state.limit + 10 }, this.getProfiles)
}
rowRenderer = (type, data) => {
return (
<TutorCard
item={data}
navigation={this.props.navigation}
liked={
this.props.auth.likedProfiles.some((user) => user.id === data._id)
? true
: false
}
/>
);
}
TutorCard.js
class TutorCard extends Component {
state = {
liked: false,
};
shouldComponentUpdate(nextProps, nextState){
if(JSON.stringify(this.props.item._id) === JSON.stringify(nextProps.item._id) &&
this.state.liked === nextState.liked){
console.log("should cmp update tutors card false")
return false
}
if(JSON.stringify(this.props.item._id) !== JSON.stringify(nextProps.item._id) ||
this.state.liked !== nextState.liked){
console.log("should cmp update tutors card true")
return true
}
}
async likedCard() {
//server request
this.setState({ liked: false });
const res = await axios.post(IP_ADDRESS + '/api/removeLikedProfile',
{ id: this.props.item._id });
this.props.fetchCurrentUser()
}
async dislikeCard() {
//server request
this.setState({ liked: true });
const res = await axios.post(IP_ADDRESS + '/api/addLikedProfile',
{ id: this.props.item._id });
this.props.fetchCurrentUser()
}
capitalize = str => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
renderHeart = () => {
if (!this.props.liked && !this.state.liked) {
return (
<TouchableOpacity onPress={() => this.dislikeCard()}>
<AntDesign name="hearto" size={normalize(23)} color="#26a03a" />
</TouchableOpacity>
);
}
if(this.props.liked || this.state.liked){
return (
<TouchableOpacity onPress={() => this.likedCard()}>
<AntDesign name="heart" size={normalize(23)} color="red" />
</TouchableOpacity>
);
}
}
render() {
return (
<View>
<Button style={{
flexDirection: 'row', flex: 1,
justifyContent: 'flex-end'
}}
transparent>{this.renderHeart()}</Button>
</View>
);
}
}

How to render only 5 items in react autosuggest?

I'am using react autosuggest npm package to get the json data and display it. I want to display only 5 items. How to do it?
Form.js
import React from 'react'
import Autosuggest from 'react-autosuggest';
import cities from 'cities.json';
const getSuggestions = value => {
const inputValue = value.trim().toLowerCase();
const inputLength = inputValue.length;
// Here I get data from cities.json
return inputLength === 0 ? [] : cities.filter(lang =>
lang.name.toLowerCase().slice(0, inputLength) === inputValue
);
);
};
const getSuggestionValue = suggestion => suggestion.name;
const renderSuggestion = suggestion => (
<div>
{console.log('suggestion', suggestion)}
{suggestion.name}
</div>
);
class Form extends React.Component {
constructor() {
super();
this.state = {
value: '',
suggestions: []
};
}
onChange = (event, { newValue }) => {
this.setState({
value: newValue
});
};
onSuggestionsFetchRequested = ({ value }) => {
this.setState({
suggestions: getSuggestions(value)
});
};
onSuggestionsClearRequested = () => {
this.setState({
suggestions: []
});
};
render(){
const { value, suggestions } = this.state;
// Autosuggest will pass through all these props to the input.
const inputProps = {
placeholder: 'Search City...',
value,
onChange: this.onChange
};
return (
<div>
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
/>
<br/>
</div>
)
}
}
export default Form;
I want to render only 5 items, otherwise, computer hangs while loading huge data. Is there any other autocomplete react npm package, since I want only cities and country list. i.e when city is inputted, automatically the city name must be suggested with its relevant country.Any solution or suggestion highly appreciated. Thanks in advance
i modified you're getSuggestions() method a little i guess this should work for you.
const getSuggestions = value => {
const inputValue = value.trim().toLowerCase();
const inputLength = inputValue.length;
// Here I get data from cities.json
return inputLength === 0 ? [] : cities.filter(lang =>
lang.name.toLowerCase().slice(0, inputLength) === inputValue
).slice(0,5);
};
Use the Slice method with start index and last Index
suggestions={suggestions.slice(0, 5)}
import {
React
,Avatar
,axiosbase
} from '../../import-files';
import Autosuggest from 'react-autosuggest';
import './autosuggest.css';
import { withStyles } from '#material-ui/core/styles';
import TextField from '#material-ui/core/TextField';
import Paper from '#material-ui/core/Paper';
import MenuItem from '#material-ui/core/MenuItem';
let suggestions = [ { label: 'Afghanistan' } ];
function renderInputComponent(inputProps) {
const { classes, inputRef = () => {}, ref, ...other } = inputProps;
return (
<TextField
className={classes.textField}
fullWidth
variant="outlined"
InputProps={{
inputRef: node => {
ref(node);
inputRef(node);
},
classes: {
input: classes.input,
},
}}
{...other}
/>
);
}
function renderSuggestion(suggestion, { query, isHighlighted }) {
return (
<MenuItem selected={isHighlighted} component="div">
<div>
<strong key={String(suggestion.id)} style={{ fontWeight: 300 }}>
<span className="sugg-option">
<span className="icon-wrap">
<Avatar src={suggestion.Poster}></Avatar>
</span>
<span className="name">
{suggestion.Title}
</span>
</span>
</strong>
</div>
</MenuItem>
);
}
function initSuggestions(value) {
suggestions = value;
}
function getSuggestionValue(suggestion) {
return suggestion.Title;
}
function onSuggestionSelected(event, { suggestion, suggestionValue, suggestionIndex, sectionIndex, method }) {
console.log('HandleSuggestion() '+suggestionValue);
}
const styles = theme => ({
root: {
height: 50,
flexGrow: 1,
},
container: {
position: 'relative',
},
suggestionsContainerOpen: {
position: 'absolute',
zIndex: 998,
marginTop: theme.spacing.unit,
left: 0,
right: 0,
overflowY: 'scroll',
maxHeight:'376%'
},
suggestion: {
display: 'block',
},
suggestionsList: {
margin: 0,
padding: 0,
listStyleType: 'none',
},
divider: {
height: theme.spacing.unit * 2,
},
});
class IntegrationAutosuggest extends React.Component {
state = {
single: '',
popper: '',
suggestions: [],
};
componentDidMount() {
initSuggestions(suggestions);
}
// Filter logic
getSuggestions = async (value) => {
const inputValue = value.trim().toLowerCase();
var _filter = JSON.stringify({
filter : inputValue,
});
return await axiosbase.post(`${apiCall}`, _filter);
};
handleSuggestionsFetchRequested = ({ value }) => {
this.getSuggestions(value)
.then(data => {
if (data.Error) {
this.setState({
suggestions: []
});
} else {
const responseData = [];
data.data.itemsList.map((item, i) => {
let File = {
id: item.idEnc,
Title: item.englishFullName +' '+item.arabicFullName,
englishFullName: item.englishFullName,
arabicFullName: item.arabicFullName,
Poster: item.photoPath,
}
responseData.push(File);
});
this.setState({
suggestions: responseData
});
}
})
};
handleSuggestionsClearRequested = () => {
this.setState({
suggestions: [],
});
};
handleChange = name => (event, { newValue }) => {
this.setState({
[name]: newValue,
});
if(event.type=='click'){
if(typeof this.props.handleOrderUserFirstNameChange === "function"){
this.props.handleOrderUserFirstNameChange(newValue);
}
this.state.suggestions.filter(f=>f.Title===newValue).map((item, i) => {
//id
//Title
// Poster
if(typeof this.props.handleUserIDChange === "function"){
this.props.handleUserIDChange(item.id);
}
});
}
};
render() {
const { classes } = this.props;
// console.log('Re-render!!');
// console.log(this.props);
// console.log(this.state.suggestions);
const autosuggestProps = {
renderInputComponent,
suggestions: this.state.suggestions,
onSuggestionsFetchRequested: this.handleSuggestionsFetchRequested,
onSuggestionsClearRequested: this.handleSuggestionsClearRequested,
onSuggestionSelected: this.props.onSelect,
getSuggestionValue,
renderSuggestion,
};
return (
<div className={classes.root}>
<Autosuggest
{...autosuggestProps}
inputProps={{
classes,
placeholder: this.props.placeHolder,
value: this.state.single,
onChange: this.handleChange('single'),
}}
theme={{
container: classes.container,
suggestionsContainerOpen: classes.suggestionsContainerOpen,
suggestionsList: classes.suggestionsList,
suggestion: classes.suggestion,
}}
renderSuggestionsContainer={options => (
<Paper {...options.containerProps} square>
{options.children}
</Paper>
)}
/>
<div className={classes.divider} />
</div>
);
}
}
export default withStyles(styles)(IntegrationAutosuggest);

How to change each of state of list item separately in react redux?

Using
react-redux
redux-persist
redux-actions
react-native
I'm learning react-redux and react-native by myself.
I'm trying to update a single item from list in react-redux now.
There's many categories and stores in my project.
An user would select one of categories, and then click 'like button' of one item in store list.
It's like instagram or facebook.
When I change one item's state, the state of every item in the store list change at the same time.
I have no idea why it happens.
I set the structure to ducks pattern to avoid change too much files when to change state.
If anyone give some advice, I would appreciate and it could be helpful for me. Thank you.
I saw some article to resolve this issue, have to give id to distinguish items and make the payload as object. I didn't understand well, so my code is messy now. But I'd like to know what happen to my code, so I share my code.
restaurantContainer.js
class RestaurantListContainer extends Component {
shouldComponentUpdate(nextProps) {
return nextProps.imgUrls !== this.props.imgUrls;
}
componentDidMount() {
const {category, StoreActions} = this.props;
try {
StoreActions.fetchStoreInfo(category);
StoreActions.fetchImgUrl(category);
this.getUid();
} catch (e) {
console.log(e);
}
}
async getUid() {
const {StoreActions} = this.props;
const uid = await storage.getItem('uid');
StoreActions.fetchLikeList(uid);
}
render() {
const {fetching, tabColor, tabName, category, categoryId, navigation, stores, imgUrls, like} = this.props;
const {onClick} = this;
return (
<View>
...
<ScrollView>
{
fetching ?
<View>
<Bars size={30} color="#40D59B"/>
</View>
:
stores.map((store, i) =>
<View key={`item-${i}`}>
<RestaurantItem
key={`restaurantItem-${i}`}
i={i}
category={category}
navigation={navigation}
storeInfo={store}
imgUrls={imgUrls[i]}
categoryId={categoryId}
like={like}
/>
</View>
)
}
</ScrollView>
</View>
);
}
}
export default connect(
({styleMod, storeMod}) => ({
stores: storeMod.stores,
imgUrls: storeMod.imgUrls,
fetching: storeMod.fetching,
likeList: storeMod.likeList
}),
(dispatch) => ({
StoreActions: bindActionCreators(storeActions, dispatch),
})
)(RestaurantListContainer);
restaurantItem.js
class RestaurantItem extends Component {
pressFunc = (item) => {
const {navigation} = this.props;
const {push} = navigation;
console.log(item.name);
push('RestaurantDetail', {info: item});
}
voteAdder = async (storeName) => {
const uid = await storage.getItem('uid');
const {i, categoryId} = this.props;
if (uid) {
const {VoteActions, LikeActions, category, favoriteStores} = this.props;
try {
VoteActions.voteAdd(favoriteStores, category, storeName, uid);
LikeActions.likeClicked(storeName, category, categoryId, i);
} catch (e) {
console.log(e);
}
} else {
alert('You are not authorized!');
}
}
render() {
const {i, storeInfo, category, categoryId, imgUrls, favoriteStores, like} = this.props;
return (
<View style={restaurantCard}>
<StoreImg
img={imgUrls}
name={storeInfo.name}
/>
<StoreInfoBlock
i={i}
storeInfo={storeInfo}
pressFunc={this.pressFunc}
/>
<View style={{flexDirection: 'column'}} >
{
<ThumbImg
voteAdder={() => this.voteAdder(storeInfo.name)}
name={storeInfo.name}
favoriteStore={favoriteStores[category]}
category={category}
like={like}
categoryId={categoryId}
/>
}
<Score count={storeInfo.count}/>
</View>
</View>
);
}
}
export default connect(
({voterMod, likeMod}) => ({
favoriteStores: voterMod.favoriteStores,
like: likeMod.like,
}),
(dispatch) => ({
VoteActions: bindActionCreators(voteActions, dispatch),
LikeActions: bindActionCreators(likeActions, dispatch),
})
)(RestaurantItem);
thumbImg.js
export default class ThumbImg extends Component {
onClick = () => {
this.props.voteAdder();
}
onFlag = () => {
const {like, categoryId, i} = this.props;
if(like.categoryById[categoryId]) {
if(like.storeById[i]) {
console.log(2);
return (
<FastImage
resizeMode={FastImage.resizeMode.cover}
style={{width: 50, height: 50}}
source={require('...')}
/>
);
} else {
return (
<FastImage
resizeMode={FastImage.resizeMode.cover}
style={{width: 50, height: 50}}
source={require('...')}
/>
);
}
} else {
return (
<FastImage
resizeMode={FastImage.resizeMode.cover}
style={{width: 50, height: 50}}
source={require('...')}
/>
);
}
}
render() {
return (
<TouchableOpacity onPress={this.onClick}>
<View style={{paddingTop: 15, paddingRight: 15}}>
{
this.onFlag()
}
</View>
</TouchableOpacity>
);
}
}
likeMod.js
// Action types
const ON_LIKE = 'like/ON_LIKE';
const OFF_LIKE = 'like/OFF_LIKE';
// action creator
export const likeClicked = (store, category, categoryId, i) => (dispatch) => {
const selectedCategory = {categoryById: {}};
const categoryInfo = {
id: categoryId,
name: category,
};
selectedCategory.categoryById[categoryId] = categoryInfo;
const selectedStore = {storeById: {}};
const storeInfo = {
id: i,
name: store
}
selectedStore.storeById[i] = storeInfo;
const favorites = {
...selectedCategory,
...selectedStore
}
dispatch({type: ON_LIKE, payload: favorites});
}
const initialState = {
like: {
categoryById: {},
storeById: {}
}
};
// Reducer
export default handleActions({
[ON_LIKE]: (state, action) => ({...state, like: action.payload}),
[OFF_LIKE]: (state, action) => ({...state, like: action.payload}),
}, initialState);

React native delete multiple items from state array

I have a directory which stores images taken using the camera. For saving images I am using RNFS. I am using react-native-photo-browser.
The gallery itself doesn't have any options to delete the items from the gallery. So I am working to achieve it
export default class GridGallery extends React.Component{
static navigationOptions = {
title: 'Image Gallery',
};
constructor(props) {
super(props)
this.state = {
filesList : [],
mediaSelected: [],
base64URI: null,
galleryList: []
}
}
componentDidMount(){
FileList.list((files) => {
if(files != null) {
this.fileUrl = files[0].path;
files = files.sort((a, b) => {
if (a.ctime < b.ctime)
return 1;
if (a.ctime > b.ctime)
return -1;
return 0;
});
this.setState({
filesList: files
});
}
console.warn(this.state.filesList);
this.getFiles();
});
}
getFiles(){
//console.warn(this.state.filesList);
const ArrFiles = this.state.filesList.map((file) =>
({ caption : file.name, photo : file.path })
);
//console.warn(ArrFiles);
this.setState({ galleryList : ArrFiles });
}
onActionButton = (media, index) => {
if (Platform.OS === 'ios') {
ActionSheetIOS.showShareActionSheetWithOptions(
{
url: media.photo,
message: media.caption,
},
() => {},
() => {},
);
} else {
alert(`handle sharing on android for ${media.photo}, index: ${index}`);
}
};
handleSelection = async (media, index, isSelected) => {
if (isSelected == true) {
this.state.mediaSelected.push(media.photo);
} else {
this.state.mediaSelected.splice(this.state.mediaSelected.indexOf(media.photo), 1);
}
console.warn(this.state.mediaSelected);
}
deleteImageFile = () => {
const dirPicutures = RNFS.DocumentDirectoryPath;
//delete mulitple files
console.warn(this.state.mediaSelected);
this.state.mediaSelected.map((file) =>
// filepath = `${dirPicutures}/${file}`
RNFS.exists(`${file}`)
.then( (result) => {
console.warn("file exists: ", result);
if(result){
return RNFS.unlink(`${file}`)
.then(() => {
console.warn('FILE DELETED');
let tempgalleryList = this.state.galleryList.filter(item => item.photo !== file);
this.setState({ galleryList : tempgalleryList })
})
// `unlink` will throw an error, if the item to unlink does not exist
.catch((err) => {
console.warn(err.message);
});
}
})
.catch((err) => {
console.warn(err.message);
})
)
}
renderDelete(){
const { galleryList } = this.state;
if(galleryList.length>0){
return(
<View style={styles.topRightContainer}>
<TouchableOpacity style={{alignItems: 'center',right: 10}} onPress={this.deleteImageFile}>
<Image
style={{width: 24, height: 24}}
source={require('../assets/images/ic_delete.png')}
/>
</TouchableOpacity>
</View>
)
}
}
goBack() {
const { navigation } = this.props;
navigation.pop;
}
render() {
const { galleryList } = this.state;
return (
<View style={styles.container}>
<View style={{flex: 1}}>
<PhotoBrowser
mediaList={galleryList}
enableGrid={true}
displayNavArrows={true}
displaySelectionButtons={true}
displayActionButton={true}
onActionButton={this.onActionButton}
displayTopBar = {true}
onSelectionChanged={this.handleSelection}
startOnGrid={true}
initialIndex={0}
/>
</View>
{this.renderDelete()}
</View>
)
}
}
An example list of images:
[
{
photo:'4072710001_f36316ddc7_b.jpg',
caption: 'Grotto of the Madonna',
},
{
photo: /media/broadchurch_thumbnail.png,
caption: 'Broadchurch Scene',
},
{
photo:
'4052876281_6e068ac860_b.jpg',
caption: 'Beautiful Eyes',
},
]
My aim is whenever the item from state galleryList is removed I need to refresh the component, so the deleted image will be removed from the gallery. So When I try to use filter the galleryList it deleting other images instead of other images:
let tempgalleryList = this.state.galleryList.filter(item => item.photo !== file);
this.setState({ galleryList : tempgalleryList })
MCVE -> This is a minified version of my code, you can see the images are deleting randomly
Problem
let tempgalleryList = this.state.galleryList.filter(item => item.photo !== file);
this.setState({ galleryList : tempgalleryList })
Since setState is async, this.state.galleryList will not be updated in each iteration of your map function, so the final updated state will only have one item filtered out instead of all selected items.
Solution
You can use the callback version of setState which uses the updated state instead:
this.setState(prevState => ({
galleryList : prevState.galleryList.filter(item => item.photo !== file),
}));
Alternative solution
Instead of calling setState in every iteration, you can call it outside of your map function instead (though setState updates will be batched anyway so no significant performance improvement):
this.setState(prevState => ({
galleryList : prevState.galleryList.filter(item => !prevState.mediaSelected.includes(item.photo)),
}));
Other problems with your code
this.state.mediaSelected.push(media.photo);
} else {
this.state.mediaSelected.splice(this.state.mediaSelected.indexOf(media.photo), 1);
You are directly mutating your state here. Do this instead:
this.setState(prevState => ({
mediaSelected: prevState.mediaSelected.concat(media.photo)
}));
this.setState(prevState => ({
mediaSelected: prevState.mediaSelected.filter(e => e != media.photo)
}));

Resources