Is it possible to use i18n localization for redux Actions? - reactjs

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.

Related

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

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.

Move a const/function in to a custom hook / re-usable piece of code

In my functional component / page I've got a const/function that I pass error messages to, that then updates a couple of useState records and logs the error to the console. It looks like this:
const catchError = (e:any, message:string) => {
//throw new Error(e)
setMessage(message);
setLoading(false);
console.error(e);
};
I'd like to move this code to a hook(?) / helper file that will allow me to import it into any other component. This would mean I can use one centralised piece of code rather than writing the same code in multiple places and avoid the associated issues.
So, I've created a new catchError.tsx file with the following content:
import { useState } from 'react';
const [ message, setMessage ] = useState("idle");
const [ loading, setLoading ] = useState(false);
export const catchError = (e:any, message:string) => {
//throw new Error(e)
setMessage(message);
setLoading(false);
console.error(e);
};
However, when I render this I get the following compile error:
Failed to compile
src/hooks/catchError.tsx Line 3:33: React Hook "useState" cannot be
called at the top level. React Hooks must be called in a React
function component or a custom React Hook function
react-hooks/rules-of-hooks Line 4:33: React Hook "useState" cannot
be called at the top level. React Hooks must be called in a React
function component or a custom React Hook function
react-hooks/rules-of-hooks
Search for the keywords to learn more about each error.
This is new territory for me.
(PS: I'm quite new to React / TypeScript and would welcome any corrections in my terminology).
If you want to reuse hook logic (like useState) you can write your own custom hooks.
I believe something like so could work, though I am not completely sure how this would be used without more context.
import { useState } from 'react';
function useCatchError() {
const [ message, setMessage ] = useState("idle");
const [ loading, setLoading ] = useState(false);
const catchError = (e:any, message:string) => {
//throw new Error(e)
setMessage(message);
setLoading(false);
console.error(e);
};
return { catchError, message, loading };
}
And be used like
export function Foo() {
const {catchError, message, loading} = useCatchError();
try {
bar();
} catch (e) {
catchError(e, e.message);
}
return (
<div>
{message ? `Error: ${message}` : loading ? "Loading" : "Foo"}
</div>
);
}
More on custom hooks in the React Docs: https://reactjs.org/docs/hooks-custom.html

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

How should I organize my React Dispatch URLs

The app I'm working on is using react-router-redux. Currently the way I handle link-clicking is I'll have the following:
clickEvent = (e) => {
e.preventDefault()
this.props.dispatch(push(`/products/${product.id}`))
}
repeating itself in many different components. Same way applied to other links as well.
Recently we have decided to make changes to the url structure and suddenly I find myself searching for all dispatch(push()) and fixing them one by one. So now I'm trying to find a way to store these urls in one single place.
The obvious and easy way I tried was by having a routing_utils.js:
import React from "react"
import { push } from "react-router-redux"
// Store all the possible urls here
export function visitHome(dispatch) {
dispatch(push('/'))
}
export function visitProductShow(dispatch, productId) {
dispatch(push(`/products/${productId}`))
}
export function visitProductReviews(dispatch, productId) {
dispatch(push(`/products/${productId}`/reviews))
}
and then using it like so:
import { visitProductShow } from "../../routing_utils"
// ... inside a component:
clickEvent = (e) => {
const { dispatch, product } = this.props
visitProductShow(dispatch, product.id)
}
or you know, just store the urls without passing in dispatch, then call them like so: dispatch(push(productShowLink(id))), either way it doesn't feel right.
Can this be handled through redux actions? If so, how can I go about it? I am looking for a better approach to handle this issue, thank you for your time.

Resources