Skip to content

Instantly share code, notes, and snippets.

@khades
Created July 6, 2019 12:25
Show Gist options
  • Save khades/3c05241284f8bd475371bc104e58be63 to your computer and use it in GitHub Desktop.
Save khades/3c05241284f8bd475371bc104e58be63 to your computer and use it in GitHub Desktop.
import * as React from "react";
import States from "../utils/states";
import Context, { IChannelNameContext } from "./context";
import { IChannelNames } from "./types";
import States from "../utils/states";
import * as API from "./api";
const Container = ({ children }: { children: any }) => {
const [channelNames, setChannelNames] = React.useState<IChannelNames>();
const fetchChannelName = React.useCallback((channelID: string) => {
if (channelNames[channelID]) {
return;
}
setChannelNames((localChannelNames: IChannelNames) => Object.assign({}, localChannelNames, { [channelID]: { state: States.LOADING } }));
API.getChannelName(channelID).then((channelName: string) => {
setChannelNames((localChannelNames: IChannelNames) => Object.assign({}, localChannelNames, {
[channelID]: {
name: channelName,
state: States.READY,
},
}));
}).catch(() => {
setChannelNames((localChannelNames: IChannelNames) => Object.assign({}, localChannelNames, { [channelID]: { state: States.NOTFOUND } }));
})
}, [channelNames])
const contextValue: IChannelNameContext = React.useMemo<IChannelNameContext>(() => ({ channelNames, fetchChannelName }), [channelNames, fetchChannelName]);
return <Context.Provider value={contextValue}>{children}</Context.Provider>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment