Home > front end >  Where is a best place to make API call using React, Redux-thunk?
Where is a best place to make API call using React, Redux-thunk?

Time:04-05

I've already checked StackOverflow.com and also the entire internet for a similar question and didn't find any, so please ignore and do not give a negative reputation if you find one as I need reputation in this moment of my life!

My code works fine but I would like to know why calling an API request inside the Action-Creator file is not a good practice and what is the replacement for it?

MyComponent.jsx

const MyComponent = () => {
   dispatch = useDispatch();
   return <div>
      <button onClick={()=>{
          dispatch(getItems("?color=xxx&manufacturer=yyy"));
      }}></button>
   </div>
}

ActionCreator.js

const getItems = (queryString) => async (dispatch) => {
 try{
   dispatch({
      type: "FETCH_REQUEST",
   });

   // >>>>>> Here is the problem! <<<<<<
   const response = await fetch("https://subname.name.com/api/"   queryString);
   const data = await response.json();

   dispatch({
      type: "FETCH_SUCCESS",
      payload: data,
   });

 }catch(error){
    dispatch({
      type: "FETCH_FAILURE",
      payload: error,
   });
 }

}

Reducer.js

const INITIAL_STATE = {
    items: [],
    isLoading: false,
    error: "",
};

const reducer = (currentState, action) => {
    switch(action.type){
        case: "FETCH_REQUEST":
            return {
                ...currentState,
                isLoading: true,
        };

        case: "FETCH_SUCCESS":
            return {
                ...action.payload,
                isLoading: false,
        };

        case: "FETCH_FAILURE":
            return {
                items: [],
                error: "An error happend when fetching main data.",
        };
    }
}

CodePudding user response:

I believe it is mainly based on what you're trying to do and what is the use case of the data.

for example, if you were trying to fetch user data to determine authentication or authorization, you should make the request as high as possible, whereas, if you are trying to fetch data that is only strictly needed on edge cases, using a button with an event listener should be fine.

Another option is using dispatch within useEffect or using a callback function dedicated to doing that.

I couldn't put it as a comment due to lack of reputation, but I've asked a more experienced developer and from what I could gather, the general response I got was - it's really depending on the data use case.

CodePudding user response:

You can Now use Redux ToolKit alongwith RTK query They also recommend to Use Typescript Nowadays

Using These Technologies will make your code more concise.

RTK query here


export const YourApi = createApi({
    reducerPath:"posts",
    baseQuery:fetchBaseQuery({
      baseUrl:"http://https://subname.name.com/api/"
    })
    endpoints:(builder) => ({
      getColor:builder.query<Your_Response_type, string|void> /** Cos you demand a string **/ {
       query:(input) => `${input}`
      }
    })
})

export const {useGetColorQuery} = YourApi 

then use it in your component using this hook


const { isLoading, isError, data, isSuccess } = useGetColorQuery(page)

return (
   <>
     {isLoading && 'Loading...'}
     {isError && 'Something went wrong'}
     {isSuccess && data}
   </>

)
  

You should read the Documentation

In this architechture redux toolkit does the same thing you did. There is nothing wrong with your architechture I also used to do it that way.

  • Related