'How do you replace data multiple times with an array of keys using a react hook?

I'm not sure if I worded the question right. Here is my problem. I am trying to translate my webpage dynamically using Cognitive Services Translator from Microsoft. I made a react hook with the translator. This works fine if I just need to translate one value in an object.

const useAzureTranslate = (data: any, lang: string, objKey: string) => {

    const [translatedData, setTranslatedData] = useState<any | null>([]);

    useEffect(() => {
        Promise.all(data.map(function (obj: any) {
            return axios({
                baseURL: endpoint,
                url: '/translate',
                method: 'post',
                headers: {
                    'Ocp-Apim-Subscription-Key': subscriptionKey,
                    'Ocp-Apim-Subscription-Region': location,
                    'Content-type': 'application/json',
                    'X-ClientTraceId': uuidv4().toString()
                },
                params: {
                    'api-version': '3.0',
                    'from': 'en',
                    'to': lang
                },
                data: [{ "text": obj[objKey] }],
                responseType: 'json'
            }).then(response => {
                // console.log(response.data)
                let translatedText = response.data[0].translations[0].text;
                return { ...obj, [objKey]: translatedText };
            }).catch((error) => {
                console.log(error.response.data.error);
                throw error;
            });
        })).then(newDataArray => {
            // console.log(newDataArray);
            setTranslatedData(newDataArray);
        }).catch(err => {
            console.log(err);
            throw err;
        });
        console.log(translatedData);

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [lang])

    return { translatedData };
}

I want to be able to have an array of keys instead of having to translate just one key value. I am not sure how to go about this.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source