I am a beginner and trying to make a photo gallery. I am using pexels api to get photos. When I first time write the code of fetch image I am getting result correctly. But if refresh the page, I am getting undefined. I checked the error state and it is null. Actually the thing is happening when I am mapping the images. But if I comment out the mapping code, then getting the photos on the console without any error.
Here is a video: Problem video | Gdrive
imageSlice.js
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';
const initialState = {
images: [],
error: null,
isLoading: false,
};
const config = {
Authorization: '563492ad6f91700001000001350d302e175b4c208aac413953d6edcc',
};
export const fetchImages = createAsyncThunk('images/fetchImages', async () => {
const res = await axios.get(
'https://api.pexels.com/v1/search?query=nature&per_page=15',
{
headers: config,
}
);
console.log('Axios:', res.data);
return res.data;
});
export const imageSlice = createSlice({
name: 'images',
initialState,
extraReducers: builder => {
builder.addCase(fetchImages.pending, state => {
state.isLoading = true;
});
builder.addCase(fetchImages.fulfilled, (state, action) => {
state.isLoading = false;
state.images = action.payload;
state.error = null;
});
builder.addCase(fetchImages.rejected, (state, action) => {
state.isLoading = false;
state.images = [];
state.error = action.error.message;
});
},
});
// export const {} = imageSlice.actions;
export default imageSlice.reducer;
store.js
import { configureStore } from '@reduxjs/toolkit';
import imageReducer from './imageSlice';
export const store = configureStore({
reducer: {
images: imageReducer,
},
});
Images.jsx
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchImages } from '../redux/imageSlice';
import Image from './Image';
const Images = () => {
const { photos } = useSelector(state => state.images.images);
const a = useSelector(state => console.log(state.images));
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchImages());
}, []);
return (
<div className="container">
<h2>Images</h2>
{photos.map(photo => (
<Image key={photo.id} image={photo} />
))}
</div>
);
};
export default Images;
Image.jsx
import React from 'react';
const Image = props => {
return (
<div>
<div className="row">
<div className="col">
<img src={props.image.src.medium} alt={props.image.alt} />
</div>
</div>
</div>
);
};
export default Image;
Why this is happening? How can I solve this problem?
CodePudding user response:
Just change :
return (
<div className="container">
<h2>Images</h2>
{photos.map(photo => (
<Image key={photo.id} image={photo} />
))}
</
div>
);
to :
return (
<div className="container">
<h2>Images</h2>
{photos && photos.map(photo => (
<Image key={photo.id} image={photo} />
))}
</div>
);