The endpoint is http://127.0.0.1:8000/api
and I can see the data if I go to that endpoint in my browser.
amazonslice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
export const getProducts = createAsyncThunk(
"amazon/getProducts",
async () => {
const response = await axios.get('http://127.0.0.1:8000/api')
return response.data;
}
)
const initialState = {
allProducts: null,
isLoading: false,
error: false,
};
export const amazonSlice = createSlice({
name: "amazon",
initialState,
reducers: {
extraReducers: (builder) => {
builder.addCase(getProducts.pending, (state, action) => {
state.isLoading = true;
})
builder.addCase(getProducts.fulfilled, (state, action) => {
state.isLoading = false;
state.allProducts = action.payload;
})
builder.addCase(getProducts.rejected, (state) => {
state.error = true;
});
},
export default amazonSlice.reducer;
store.js
import { configureStore } from "@reduxjs/toolkit";
import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import amazonReducer from "./amazonSlice";
import { ThunkMiddleware } from "@reduxjs/toolkit";
import thunk from 'redux-thunk';
const persistConfig = {
key: 'root',
version: 1,
storage,
}
const persistedReducer = persistReducer(persistConfig, amazonReducer)
// The Global Store Setup
export const store = configureStore({
reducer: {amazon: persistedReducer},
middleware: [thunk]
});
export let persistor = persistStore(store)
productfeed.js
import React,{ useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getProducts } from '@/slices/amazonSlice'
const ProductFeed = () => {
const dispatch = useDispatch();
const allProducts = useSelector((state) => state.amazon);
useEffect(() => {
dispatch(getProducts())
}, [])
console.log(allProducts)
return (
<div>
some paragraph
</div>
)
}
export default ProductFeed
When I run productfeed.js
in browser, I can see the api request in the network
tab but the data are show as allProducts: Array(0)
in console but in network
tab, the data are being fetched with 200
status. Any other redux
usecase in my application working fine. I am just trying to make api
request in the redux since people told me it is a good practice.