I am learning react js and redux. I am trying to fetch some images from jsonplaceholder. Their image api is "https://jsonplaceholder.typicode.com/photos". No error is showing on the browser console. But there is no data. I can't find why the data is not fetching.
Here is my code.
imageSlice.js
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
const initialState = {
images: [],
error: null,
isLoading: false,
};
export const fetchImages = createAsyncThunk('images/fetchImages', async () => {
const res = await axios.get('https://jsonplaceholder.typicode.com/photos');
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;
});
},
});
// Action creators are generated for each case reducer function
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';
const Images = () => {
const { images } = useSelector(state => state.images);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchImages());
}, []);
console.log(images);
return (
<div className='container'>
<h2>Images</h2>
</div>
);
};
export default Images;
On the Images.jsx file, in line no 9, I am fetching data from jsonplaceholder. But not getting any data?
Here is image of console
Where is my fault? How to solve the problem?