36
loading...
This website collects cookies to deliver better user experience
thunk
middleware when creating our store, we are able to use asynchronous logic to interact with our store, More on that later.//actions/crypto.js
export const getCryptos = () => {
return (dispatch) => {
fetch("http://localhost:3000/cryptos")
.then(resp => resp.json())
.then(cryptos => {
dispatch({
type: "GET_CRYPTOS",
payload: cryptos
})
})
}
}
dispatch
within that fetch is trying to send a state update to our store. We can follow a similar layout for our fetch request if trying to post to our backend as well (below).//actions/portfolio.js
export const createPortfolio = (portfolio) => {
return (dispatch) => {
fetch(`http://localhost:3000/users/${localStorage.user}/portfolios`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(portfolio),
})
.then((response) => response.json())
.then((portfolio) => {
dispatch({ type: "CREATE_PORTFOLIO", payload: portfolio})
})
}
}
//reducers/cryptoReducer.js
const initialState = {
cryptos: [],
loading: false
}
const cryptosReducer = (state = initialState, action ) => {
switch(action.type) {
case "GET_CRYPTOS":
return {
...state,
cryptos: [...state.cryptos, ...action.payload]
}
default:
return state
}
}
...state
. By spreading the state, we are able to keep the previous state as well as add or overwrite information in the new state. Without doing this we would overwrite the state with our new information and destroy the old information. This is not what we want to do as a reducer is meant to be a pure function in which we do not mutate the state.//index.js
const store = createStore(rootReducer, compose(applyMiddleware(thunk), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()))
//index.js
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
//App.js
const mapStateToProps = (state) => {
return{
cryptos: state.cryptos,
portfolio: state.portfolio,
loading: state.loading
}
}
props.cryptos.map
and pass this information in my case to a card component which would loop each individual crypto within props.cryptos and create a list with the information I specify within my card component.export default connect(mapStateToProps)(Component);
mapDispatchToProps
is received by default. If you want to specify you would write it like this:export default connect(mapStateToProps, { getCryptos, getPortfolio })(App);
const mapDispatchToProps = dispatch => {
return {
addItem: () => {
dispatch(addItem())
}
};
};
import { connect } from 'react-redux';
import { Provider } from 'react-redux'
import { applyMiddleware, createStore, compose } from 'redux'
import { combineReducers } from 'redux'
import ReactDOM from 'react-dom';
import thunk from 'redux-thunk';