35
loading...
This website collects cookies to deliver better user experience
redux
and react-redux
. The middleware redux-thunk
should also be installed if your store requires asynchronous logic (I'll be using this in my examples).//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter as Router} from 'react-router-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import reducer from './reducers/Reducer';
const store = createStore(reducer, applyMiddleware(thunk));
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
createStore
method from Redux, which takes two arguments: our future reducer, and a method to apply our Thunk middleware. We use the <Provider />
component with our store as a property to allow its children access to our store and thus our application's state.combineReducers
method which sends the relevant action to the correct reducer.//Reducer.js
import { combineReducers } from "redux";
const reducer = combineReducers({
contents: contentsReducer,
reviews: reviewsReducer
});
export default reducer;
function contentsReducer(state = [], action) {
switch (action.type) {
case "GET_CONTENT":
return [...state, ...action.contents]
case "CREATE_CONTENT":
return[...state, action.content];
case "DELETE_CONTENT":
return[...state].filter(elem => elem.id !== action.payload);
default:
return state;
}
}
function reviewsReducer...
useSelector
and useDispatch
hooks from react-redux
. The former allows us to connect to our store's state while the latter allows us to connect to our dispatch function from our store. We'll be dispatching actions to go from our current state to our new state in our component. I used the useEffects
hook from react
to dispatch my fetchContents
action when the Contents List component mounted.//contentActions.js
export const fetchContents = () => {
return (dispatch) => {
fetch("http://localhost:3000/contents")
.then(response => response.json())
.then(data => {
dispatch({ type: "GET_CONTENT", contents: data });
})
.catch(fail => alert(fail));
};
};
//ContentList.js
import { useSelector, useDispatch } from 'react-redux';
import { useEffect } from 'react';
import { fetchContents } from '../actions/contentActions';
export default function ContentList() {
const contents = useSelector((state) => state.contents)
const dispatch = useDispatch()
useEffect(() => {
if (contents.length === 0) {
dispatch(fetchContents())
}
}, [])