'Undefined Return for Context API
I've been getting an undefined in home.js when I try to console.log(products)
I tried to use postman, and it can successfully get the data from the database, also inside apicalls.js, when I try to console.log(res.data).
Am I missing something? I tried to copy in the tutorial, but it didn't work for me.
apicalls.js
import axios from 'axios'
import {
getProducstStart,
getProductsFailure,
getProductsSuccess,
} from './ProductAction'
export const getProducts = async (dispatch) => {
dispatch(getProducstStart())
try {
const res = await axios.get('/product')
dispatch(getProductsSuccess(res.data))
} catch (error) {
dispatch(getProductsFailure())
}
}
home.js
import React, { useContext, useEffect } from 'react'
import { getProducts } from '../../context/ApiCalls'
import { ProductContext } from '../../context/ProductContext'
const Home = () => {
const { products, dispatch } = useContext(ProductContext)
useEffect(() => {
getProducts(dispatch)
}, [dispatch])
console.log(products)
return (
<div className="home">
</div>
)
}
ProducetReducer.js
const ProductReducer = (state, action) => {
switch (action.type) {
case 'GET_PRODUCT_START':
return {
products: [],
isFetching: true,
error: false,
}
case 'GET_PRODUCT_SUCCESS':
return {
products: action.payload,
isFetching: false,
error: false,
}
case 'GET_PRODUCT_FAILURE':
return {
products: [],
isFetching: false,
error: true,
}
default:
return { ...state }
}
}
export default ProductReducer
ProductContext.js
import { createContext, useReducer } from 'react'
import ProductReducer from './ProductReducer'
const INITIAL_STATE = {
products: [],
isFetching: false,
error: false,
}
export const ProductContext = createContext(INITIAL_STATE)
export const ProductContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(ProductReducer, INITIAL_STATE)
return (
<ProductContext.Provider
value={{
products: state.products,
isFetching: state.isFetching,
error: state.error,
dispatch,
}}
>
{children}
</ProductContext.Provider>
)
}
index.js
import { createRoot } from 'react-dom/client'
import App from './App'
import { ProductContextProvider } from './context/ProductContext'
const container = document.getElementById('root')
const root = createRoot(container)
root.render(
<ProductContextProvider>
<App />
</ProductContextProvider>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
