I'm learning Redux. Here I tried to build a simple app to understand the concept. Why can't I get listings in App.js? I've passed it from index.js through dispatch and I'm trying to receive it in useEffect in App.js.
index.js
I'm passing mockData as listings from index.js to App.js
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
import App from './App';
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
const mockData = [
{
name: "Barry Johnson",
age: 43,
},
{
name: "Chris Evan",
age: 25,
},
];
const getAll = () => {
return mockData;
};
const listingsReducer = (state = [], action) => {
switch (action.type) {
case 'INIT_LISTINGS':
return action.data;
default:
return state;
}
};
export const initListings = () => {
return async dispatch => {
const listings = await getAll();
dispatch({
type: 'INIT_LISTINGS',
data: listings,
});
};
};
const store = createStore(listingsReducer, applyMiddleware(thunk));
root.render(
<StrictMode>
<Provider store={store}>
<App />
</Provider>
</StrictMode>
);
App.js
Here inside useEffect where I'm logging listings, I'm getting undefined.
import React from "react";
import "./style.css";
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { initListings } from './index.js';
export default function App() {
const dispatch = useDispatch();
const listings = useSelector((state) => state.listings)
useEffect(() => {
dispatch(initListings());
console.log(listings);
}, [dispatch]);
return (
<div>
<div className="App">
<p>Start editing to see some magic happen :)</p>
</div>
</div>
);
}
CodePudding user response:
In your reducer function use this listings is your reducer function :-
const listingsReducer = (state = {}, action) => {
switch (action.type) {
case 'INIT_LISTINGS':
return {...state, listings : action.payload};
default:
return state;
}
};