Language used : JS with REACT REDUX
Here is the context: I have a page where the user can see all the forms made.
At the initialization of my application, I dispatch 'get forms'. this dispatch allows me via axios to retrieve all the forms I have in db
useEffect(() => {
dispatch(getForms());
}, []);
i have an action and reducer file :
actions
import axios from "axios";
export const GET_ALL_FORMS = "GET_ALL_FORMS";
export const getForms = () => (dispatch) =>
axios
.get(`/api/form`)
.then((res) => {
dispatch({ type: GET_ALL_FORMS, payload: res.data });
})
.catch((err) => err);
reducer
import { GET_ALL_FORMS } from "../actions/forms.actions";
const initialState = [];
export default function allFormsReducer(state = initialState, action) {
switch (action.type) {
case GET_ALL_FORMS:
return action.payload;
default:
return state;
}
}
Then in my "folder" page I use 'useSelector' to retrieve all the forms and display them (working).
import React, { useState, useEffect } from "react";
import { useSelector } from "react-redux";
export const FolderNew = () => {
const formData = useSelector((state) => state.allFormsReducer);
But now, at the click of a button, I would like to sorted my forms by date
Normally I don't use redux, so I would just do an axios request in my folder page and then use 'useState' (allForms, setAllForms) with my res.data and refresh the state like this :
const descend = () => {
const sorted = [...allForms].sort((a, b) =>
b.createdAt.localeCompare(a.createdAt)
);
setAllForms(sorted);
};
But now, with redux i'm really lost.
What i'm actually trying : Change the reducer to sort here the state (not working for the moment)
You can create a dispatch action something like sortForms(), then write the logic in your reducer:
export default function allFormsReducer(state = initialState, action) {
switch (action.type) {
case 'SORT_ALL_FORMS': {
const sortedForms = ....
return sortedForms
}
}
}
As Redux documents state, you should put as much logic as possible in your reducers:
https://redux.js.org/style-guide/#put-as-much-logic-as-possible-in-reducers