Home > Back-end >  Data is not stored in redux
Data is not stored in redux

Time:07-21

I am trying to extend my frontend code with another redux call but the data is not appearing in store.

Here is store definition

const store = configureStore({
    reducer: {
        login: loginSlice.reducer,
        cart: cartSlice.reducer,
        product: productSlice.reducer,
        notification: notificationSlice.reducer
    }
});

Here is a slice

const productSlice = createSlice({
    name: 'product',
    initialState: {
        products: []
    },
    reducers: {
        replaceData(state,action) {
            console.log(action)
            state.products = action.payload.products;
        }
    }
  
});

export const productActions = productSlice.actions

export default productSlice

And action

export const fetchProducts = () => {
    return async (dispatch) => {
        const fetchHandler = async () => {
            const resp = await fetch("https://shoppingcart-a62bb-default-rtdb.europe-west1.firebasedatabase.app/products.json")
            const data = await resp.json();
            
        }

        try {
            const productData = await fetchHandler();
            dispatch(productActions.replaceData(productData))
        } catch (err) {
            dispatch(notificationActions.showNotification({
                open: true,
                message: "Error reading product data",
                type: 'error'
            }));
        }
    }
}

That's what I call in APP.js

   useEffect(()=>{
     dispatch(fetchCartData())
     dispatch(fetchProducts())
   },[dispatch]);

Here I read data from store in component

let respProducts = useSelector(state => state.product.products);
     console.log(respProducts)

The problem is that fetch in action works,but payload in dispatch empty and no data in useSelector.

I really don't get what's wrong as similar code in the same app works.

CodePudding user response:

Your fetchHandler is missing a return statement.

        const fetchHandler = async () => {
            const resp = await fetch("https://shoppingcart-a62bb-default-rtdb.europe-west1.firebasedatabase.app/products.json")
            const data = await resp.json();
            return data            
        }

CodePudding user response:

use 'useReduxSelector' instead of 'useSelector'

  • Related