I am just making a simple app to learn async with redux. I have gotten everything working, now I just want to display the actual state onto the web-page. Now, how do I actually access the store's state in the render method?
Here is my code (everything is in one page because I'm just learning):
const initialState = { fetching: false, fetched: false, items: [], error: null } const reducer = (state=initialState, action) => { switch (action.type) { case "REQUEST_PENDING": { return {...state, fetching: true}; } case "REQUEST_FULFILLED": { return { ...state, fetching: false, fetched: true, items: action.payload } } case "REQUEST_REJECTED": { return {...state, fetching: false, error: action.payload} } default: return state; } }; const middleware = applyMiddleware(promise(), thunk, logger()); const store = createStore(reducer, middleware); store.dispatch({ type: "REQUEST", payload: fetch('http://localhost:8000/list').then((res)=>res.json()) }); store.dispatch({ type: "REQUEST", payload: fetch('http://localhost:8000/list').then((res)=>res.json()) }); render( <Provider store={store}> <div> { this.props.items.map((item) => <p> {item.title} </p> )} </div> </Provider>, document.getElementById('app') );
So, in the render method of the state I want to list out all the item.title
from the store.
Thanks
It's simple to get access to the store inside a React component – no need to pass the store as a prop or import it, just use the connect function from React Redux, and supply a mapStateToProps function that pulls out the data you need. Then, inside the component, you can pass that data to a function that needs it.
The state in Redux is stored in memory. This means that, if you refresh the page the state gets wiped out. The state in redux is just a variable that persists in memory because it is referenced by all redux functions.
You should create separate component, which will be listening to state changes and updating on every state change:
import store from '../reducers/store'; class Items extends Component { constructor(props) { super(props); this.state = { items: [], }; store.subscribe(() => { // When state will be updated(in our case, when items will be fetched), // we will update local component state and force component to rerender // with new data. this.setState({ items: store.getState().items; }); }); } render() { return ( <div> {this.state.items.map((item) => <p> {item.title} </p> )} </div> ); } }; render(<Items />, document.getElementById('app'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With