What is the best practice for useAxios hook with Redux's slice? - reactjs

I've created a useAxios hook to use for Axios calls and also reduxjs/toolkit for handling React data. Is it the correct practice to use them together?
For example, in slice.js
export const getTodo = (data) => async (dispatch) => {
try {
const response = await axios.get(`${URL}/${data}`);
dispatch(getTodo(response.data));
} catch (err) {
throw new Error(err);
}
};
When I replace await axios.get(`${URL}/${data}`); to useAxios()hook, I got the error: hooks can only be called inside of the body of a function component.
What is the best practice for Redux to use the Axios hook? or it's not possible? Any good example? Thanks!

*The only place you can ever call a React hook is inside of a function component, or another hook. You can never call a hook anywhere else.

Related

use Custom hook in a non functional api file

I have a api file that I would like to store all my api calls and use react query to call those api function, however I have some endpoint which are private and I use a custom hooks for that logic. Issue is I cannot call the custom hook in the api file as it is not a functional component? How do I handle this
//api file
import useAxiosPrivate from "../hooks/useAxiosPrivate";
export const GetPackagesinfo = async () => {
const axiosPrivate = useAxiosPrivate();
const res = await axiosPrivate.get(
"/mk_get_packages_information"
);
return res.data;
};
export const GetAccountInfo = async () => {
const axiosPrivate = useAxiosPrivate();
const res = await axiosPrivate.get(
"/mk_company_admin_user_account_information"
);
return res.data;
};
export const DeleteAcccount = async () => {
const axiosPrivate = useAxiosPrivate();
const res = await axiosPrivate.delete(
"/mk_company_admin_user_delete_account_information"
);
return res.data;
};
if i try to use as above i get the error
Invalid hook call. Hooks can only be called inside of the body of a function component. This
could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
In short, you can't (as the warning mentions).
I don't know what is in useAxiosPrivate, but you can extract the non-React parts of that into its own non-hook function. Then both api.js and useAxiosPrivate.js can import the non-hook function.
You can't use hooks in react-query 's queryFn.
While react-query will apply your function inside like:
useSyncExternalStore(
useCallback(
()=>{
useAxiosPrivate()
},[]
),
()=>{}
)
It break the rules of React hooks.
See https://reactjs.org/warnings/invalid-hook-call-warning.html#breaking-the-rules-of-hooks
I did not find any alternative so I just copypasted each api function to its target component/page and used it from there and i was able to use my hooks as intended

Is it possible to use i18n localization for redux Actions?

I was trying to implement i18n localization for Redux Action functions, but i constantly recieve different hook errors. When i implemented i18n this way i recieve error.
Line 428:17: React Hook "useTranslation" is called in function "sendDataRequest" that is neither a React function component nor a custom React Hook function.
import { useTranslation } from "react-i18next";
export const sendDataRequest = (requestId) => {
const { t } = useTranslation();
return async (dispatch) => {
try {
dispatch(sendDataRequest());
await dataAPI.sendDataRequest({ requestId });
notification.success({
message: t('infoPage.requestSentSuccessfully'),
});
dispatch(sendDataSuccess());
} catch (error) {
dispatch(sendDataFailure());
console.error(error);
}
}
}
Then i moved const { t } = useTranslation(); inside of return statement.
But then i recieved another error
It looks like I obviously using it wrong here.
But i cannot find any examples on i18n being used in Actions.
Does anyone knows is it even possible to use i18b in Actions?
Check out https://github.com/i18next/react-i18next/issues/909
You need to gain access to your i18next instance. The one you create somewhere in your codebase. With this instance you can simply call i18n.t("my.translation.key") to translate. This is completely independent from react.

How to stop the multiple API request in react js functional component

I am new in react js. I have a function and one GET API request. I need to dispatch the API action in the functional component. When I call the dispatch function in my functional component. It's re-render multiple times (Multiple requests coming). When I use the dispatch inside the useEffect My API is not dispatched.
Without useEffect dispatch function called:(API called multiple times)
export default LogoCard {
let id=1;
const dispatch = useDispatch();
dispatch(viewLogDetails(id));
}
using useEffect dispatch function called.(dispatch function not called using useEffect)
export default LogoCard {
let id=1;
const dispatch = useDispatch();
useEffect(()=>{
dispatch(viewLogDetails(id));
},[dispatch]);
}
Redux Action:
export const viewTimeLogging = createAsyncThunk(
"logoReducer/logo/Viewlogo",
async (id, { getState }) => {
const response = await axios.get(`/viewLogDetails?id=${id}`);
let data = null;
data = await response.data;
return data.viewLogo;
}
);
I've noticed that the method you are calling inside your dispatch has a different name.
If you need the axios method to be called only when id changes you should use the useEffect hook with [dispatch, id] dependencies (I assume that you will pass the id as a props or gather it in some other way in the future instead of having hardcoded like that).
If you want to call the dispatch on every re-render of the component you can either put it inside the function like the first piece of code you wrote (but I would not do that).
https://codesandbox.io/s/mystifying-raman-tul4j?file=/src/App.js
Here's a sandbox with the code you might want

how to use the api data res with hooks

Hi i know this question its a little dumb but im learning to use react native with hooks and some things give me troubles to understand.
I have this api call with axios
const getRFC = ({vLastName,vSecondLastName,vName,vSecondName,vBirthDate}) => {
axios. post(`http://exitusdesarrollo.eastus2.cloudapp.azure.com/AppForceControllers/controllers/GetRfcController.php`, { vName, vSecondName, vLastName, vSecondLastName, vBirthDate })
.then(res => {
console.log(res.data.resultRFC);
})
}
and yeah in console log prints what i need, so what i dont know how to do it is how to use the res.data.resultRFC outside the function.
normally it would be something like
`const RFC= res.data.resultRFC;
this.setState({ RFC});`
but since im using hooks this throws me error, any advice?
use useState inside your function:
import React, { useState } from 'react';
// inside your component
const [rfc, setRfc] = useState(null);
// inside your axios callback
setRfc(res.data.resultRFC);
// later in your component / render you can use rfc
{rfc && <Text>{rfc}</Text>}
for more reference: https://reactjs.org/docs/hooks-state.html

should i use action or create reusable function for CRUD in React Hook

I am trying to understand React hook (useReducer, useEffect), what is the best way to create crud to hit on API with React hook?
should I create the function for fetch, delete, add, update in action ? then call it on reducer ? or create another reusable function and call it on the action ? or create reusable function crud and use it on components?
let say that I want to add a task
async function addTask(payload){
try {
const { data } = await axios.post(endppoint, payload)
return data
} catch(e){
console.log(e)
}
}
async function getTask() {
try {
const { data } = await axios.get(endppoint)
return data
} catch(e){
console.log(e)
}
}
where i should call those functions if I use React Hook?
i have read some articles but i just want to make sure those, for example, to hit to API

Resources