How can I refactor this code to conform best practices? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can I refactor this code to conform best practices?

import React, { useEffect, useState } from 'react'; export default TestComponent = (props) => { const [state1, setState1] = useState(props.prop1); useEffect(async () => { let functionRes = null; callTestFunction().then((output) => { functionRes = output; }); await setState1(functionRes); }) return ( ... ) }

15th Mar 2022, 10:07 AM
MD. Jashim Uddin
MD. Jashim Uddin - avatar
2 Answers
+ 4
Since you are using an async function, you don't need to use promises (.then) useEffect(async () => { const output = await callTestFunction(); await setState1(output); }); if you have error exception handling promise (.catch), you can use try catch useEffect(async () => { try { const output = await callTestFunction(); await setState1(output); } catch (err) { console.error('callTest failed ', err); } });
15th Mar 2022, 11:45 PM
Calviղ
Calviղ - avatar
0
Calviղ Thanks
16th Mar 2022, 12:31 AM
MD. Jashim Uddin
MD. Jashim Uddin - avatar