Reputation: 1356
HW assignment is asking us to use React, Redux, and Redux-Thunk to return JSON data from a provided endpoint called url
in an excel type table.
I was able to return the appropriate data in a table by JUST using React Hooks and Axios as you'll see in the codesandbox.
What could be a simple way to implement Redux and Thunk into this mix?
My thinking could be to:
Set up store.js for Redux to create store and initialize state
Create Action folder => create dataActions.js => write a action function that has the useEffect method with the Axios get request
Create Reducer folder => create dataReducer.js => write a reducer that initializes state => export default function that has a switch statement that returns the state of the data retrieved and then a default statement for anything else
All this extraneous adding of Redux/Thunk is to see if I'm able to connect all the parts together, even though we don't need it for this particular assignment. Not sure how to incorporate these 2 on top of the solution.
I'd appreciate any pointers or tips to get me on the right track.
Upvotes: 1
Views: 4228
Reputation: 11848
Essentially to convert your sample to use Redux you should:
Create reducer which will accept actions and modify store.
Here is example
const initalState = {
usersData: [],
isLoading: false,
isError: false,
errorMsg: ""
};
function reducer(state = initalState, action) {
switch (action.type) {
case "REQUEST_USERS_DATA":
return {
...state,
isLoading: true,
isError: false,
errorMsg: ""
};
case "RECEIVE_USERS_DATA":
return {
...state,
usersData: action.usersData,
isLoading: false,
isError: action.isError,
errorMsg: action.errorMsg
};
default:
return state;
}
}
Create action creator for requesting users data
export const requestUsers = url => async dispatch => {
dispatch({
type: "REQUEST_USERS_DATA"
});
try {
const json = await axios.get(url);
dispatch({
type: "RECEIVE_USERS_DATA",
usersData: json.data,
isError: false,
errorMsg: ""
});
} catch (e) {
dispatch({
type: "RECEIVE_USERS_DATA",
usersData: [],
isError: true,
errorMsg: e
});
}
};
Action creator will dispatch actions to reducer and also request data using axios.
Create store with thunk middleware to be able to dispatch functions as actions.
export const store = createStore(reducer, applyMiddleware(thunkMiddleware));
Use <Provider store={store}>
in App
component to provide store to all children.
Extract rendering logic to separate component, say TableComponent
which will dispatch actions and receive data from Redux. Redux now supports it own hooks, so you can use useSelector
and useDispatch
to access Redux in hooks style.
const { usersData, isError, isLoading, errorMsg } = useSelector(
state => state
);
const dispatch = useDispatch();
And here is working sample.
Upvotes: 2