简体   繁体   中英

how to return a function from react hook which internally uses a promise to get the value

I am new to React and want to create a react hook which returns a function and this function uses a promise internally to get the actual value. Here is my sample code -

export const useMyCustomHook = () => {

    let transKey = "";
    const [value, setValue] = useState("");
    const service = useContext(serviceContext);

    const getValue = (key: string) => {
        transKey = key
        return value
    }

    useEffect(() => {
        if (service) {
            service.GetValue(transKey).then((res: any) => {
                setValue(res);
            });
        }
    }, []);

    return getValue;
};

Here is the usage -

const getValue = useMyCustomHook()

return (
    <div className="childComponent">
        <p>Page Title: {getValue('Key1')}</p>
        <p>Page Title: {getValue('Key2')}</p>
    </div>
)

I am getting the same value for each call.

Instead of returning a function, return a value directly:

 export const getValue = (transKey) => { const [value, setValue] = useState(""); const service = useContext(serviceContext); useEffect( () => { service?.GetValue(transKey).then(setValue); }, // TODO: cleanup [service, transKey]); return value; }; // ----------------- return ( <div className="childComponent"> <p>Page Title: {getValue('Key1')}</p> <p>Page Title: {getValue('Key2')}</p> </div> )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM