Reputation: 49
use redux for calling api from django . Django server running. We make store like :
import { applyMiddleware, combineReducers, createStore } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
import { productListReducer } from "./reducers/productReducers";
const reducer = combineReducers({
productList: productListReducer,
});
const initialState = {};
const middleware = [thunk];
const store = createStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;
and my product Reducers is :
import {
PRODUCT_LIST_FAIL,
PRODUCT_LIST_REQUEST,
PRODUCT_LIST_SUCCESS,
} from "../constants/productConstants";
export const productListReducer = (state = { products: [] }, action) => {
switch (action.type) {
case PRODUCT_LIST_REQUEST:
return { loading: true, products: [] };
case PRODUCT_LIST_SUCCESS:
return { loading: false, products: action.payload };
case PRODUCT_LIST_FAIL:
return { loading: false, error: action.payload };
default:
return state;
}
};
ProductAction :
import axios from "axios";
import {
PRODUCT_LIST_FAIL,
PRODUCT_LIST_REQUEST,
PRODUCT_LIST_SUCCESS,
} from "../constants/productConstants";
export const listProducts = () => async (dispatch) => {
try {
dispatch({ type: PRODUCT_LIST_REQUEST });
const { data } = await axios.get("/api/products/");
console.log("Loading..")
console.log(data)
dispatch({
type: PRODUCT_LIST_SUCCESS,
payload: data
});
} catch (error) {
dispatch({
type: PRODUCT_LIST_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};
HomeScreen.js
import { useDispatch } from 'react-redux'
import { listProducts } from "../actions/productActions";
const dispatch = useDispatch()
useEffect(() => {
dispatch(listProducts())
}, [dispatch]);
When we calling api using useEffect we not get the api data . we get empty data and also get Error: Actions may not have an undefined "type" property. Have you misspelled a constant. Please help me to solve this question .
in here i give u some photo ,
Upvotes: 1
Views: 161
Reputation: 5033
This dispatch(listProducts())
needs to be listProducts(dispatch)
because listProducts has calls to dispatch.
Upvotes: 0