I would love some guidance/feedback in the following. Whenever I develop a react app I like to stick to a flux like pattern, I don't mind the boilerplate as I believe it gives me a pretty structured approach in which to develop my apps. It's just a personal preference, but I'm starting to notice some of the drawbacks when it comes to adding some new functionalities in the fetching data department. So usually this is what my typical app looks like.
an api.js file with an API class that returns an axios instance.
import axios from axios
export default class Api {
static allMessages(){
return axios({
method: "get",
url: "/messages",
headers:{
accept: "application/json",
"Content-Type": "application/json"
}
})
}
}
my constants.js
export const MESSAGES_LOADING = "MESSAGES_LOADING";
export const MESSAGES_SUCCESS = "MESSAGES_SUCCESS";
export const MESSAGES_ERROR = "MESSAGES_ERROR";
my messageActions.js
export const loadMessages = () => async (dispatch) => {
dispatch({ type: MESSAGES_LOADING });
try {
const messages = await Api.allMessages();
return dispatch({ type: MESSAGES_SUCCESS, messageList: messages.data });
} catch (error) {
return dispatch({ type: MESSAGES_ERROR, error: error.message });
}
};
and last but not least, my messageReducer.js
const initialState = {
messages: [],
loading: false,
error: "",
};
const messages = (state = initialState, action) => {
switch (action.type) {
case MESSAGES_LOADING:
return { ...state, loading: true, error: "" };
case MESSAGES_SUCCESS:
return { ...state, messages: action.messageList, loading: false };
case MESSAGES_ERROR:
return { ...state, error: action.error, loading: false };
default:
return state
}
};
export default messages;
what I'd like to achieve is to implement SWR on this message async call. The problem that i've encountered is that SWR is a hook and as we can see above these we're working with pure functions. has anyone encountered a way to implement SWR on an application structured as it is above?
What i've attempted so far is to create a custom SWR hook and when used directly on the component works like a charm, what i'd like to do is to add it to my actions as some other calls would require extensive side effects when working with them what I showed above is for illustration purposes.
the hook that I created looks as such useSWRList.js
import useSWR from "swr";
export const useSWRList = () => {
const fetcher = (url) =>
axios({
method: "get",
url: url,
headers: {
accept: "application/json",
"Content-Type": "application/json",
},
});
const { data, error } = useSWR("/messages", fetcher);
return {
data,
error,
};
};
how could I add this to my messageActions?
Has anyone here ever attempted to do this and if so, could you give me some feedback please. Anything could be greatly appreciated. what would you recommend to achieve a SWR like behaviour in this sort of setup.