react-use#useCookie TypeScript Examples

The following examples show how to use react-use#useCookie. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: useAcceptCookies.ts    From storefront with MIT License 6 votes vote down vote up
export default function useAcceptCookies() {
  const [acceptedCookies, setAcceptedCookies] = useCookie(COOKIE_NAME);

  const handleAcceptCookies = () => {
    setAcceptedCookies('accepted', { expires: 365 });
  };

  return {
    acceptedCookies: acceptedCookies === 'accepted',
    handleAcceptCookies,
  };
}
Example #2
Source File: Upload.tsx    From yugong with MIT License 4 votes vote down vote up
Upload: React.FC<UploadProps> = ({ label, defaultImg, onChange }) => {
  const [img, setimg] = useState<string>();
  const [isloading, setIsloading] = useState(false);
  const [viewImg, setViewImg] = useState(false);
  const [wh, setWh] = useState(' ');
  const moduleId = useSelector(
    (state: RootState) => state.activationItem.moduleId,
  );
  const [csrfToken] = useCookie('csrfToken')
  
  const ref = useRef(null);

  // 创建临时图片文件
  const createTempImg = useCallback((url: string) => {
    const wrap = ref.current as any;
    if (wrap) {
      (ref.current as any).innerHTML = '';
      const image = new Image();
      image.src = url;
      image.onload = () => {};
      (ref.current as any).appendChild(image);
    }
  }, []);

  // 获取文件宽高属性
  const getTempImgWH = useCallback(() => {
    const image = (ref.current as any)?.querySelector('img');
    if (image) {
      const str = `宽:${image.offsetWidth}px 高:${image.offsetHeight}px`;
      setWh(str);
    }
  }, []);

  // 删除临时文件

  useEffect(() => {
    setimg(defaultImg);
    if (defaultImg) {
      createTempImg(defaultImg);
    }
  }, [createTempImg, defaultImg, moduleId]);

  const onChangeUpload = useCallback(
    (info: UploadChangeParam) => {
      if (info.file.status === 'uploading') {
        setIsloading(true);
      }

      if (info.file.status === 'error') {
        setIsloading(false);
      }

      if (info.file.response) {
        setTimeout(() => {
          setIsloading(false);
          setimg(info.file.response.fileUrl);
          createTempImg(info.file.response.fileUrl);
        }, 1000);

        if (onChange instanceof Function) {
          onChange(info.file.response.fileUrl);
        }
      }
    },
    [createTempImg, onChange],
  );

  const hideView = useCallback(() => {
    setViewImg(false);
  }, []);

  const showView = useCallback(() => {
    getTempImgWH();
    setViewImg(true);
  }, [getTempImgWH]);

  const deleteImage = useCallback(() => {
    setimg('');
    if (onChange instanceof Function) {
      onChange('');
    }
  }, [onChange]);

  const inputOnChange = useCallback(
    (e) => {
      const url = e.target.value;
      if (onChange instanceof Function && isUrl(url)) {
        onChange(url);
        setimg(url);
        createTempImg(url);
      }
    },
    [createTempImg, onChange],
  );

  return (
    <>
      <Row className={s.row} gutter={4}>
        <Col className={s.label} span={7}>
          {label || ''}
        </Col>
        <Col span={14}>
          <div className={s.button}>
            {process.env.REACT_APP_DEMO === 'true' ? (
              <Tooltip
              overlayInnerStyle={{width: 400}}
                title={
                  <Input style={{width: '100%'}} value={img} onChange={inputOnChange} placeholder="输入图片url" />
                }
              >
                <span
                  className={classNames(s.uploadicon, s.empty, s.flid)}
                  style={{
                    backgroundImage: `url(${!isloading && img ? img : ''})`,
                  }}
                >
                  {isloading ? antIcon : null}
                  {!img ? <PictureOutlined /> : null}
                </span>
              </Tooltip>
            ) : (
              <UploadPic
                accept=".jpg,.jpeg,.png"
                action={'/api/upload'}
                onChange={onChangeUpload}
                showUploadList={false}
                disabled={isloading}
                headers={{
                  'x-csrf-token': csrfToken || ''
                }}
              >
                <span
                  className={classNames(s.uploadicon, s.empty, s.flid)}
                  style={{
                    backgroundImage: `url(${!isloading && img ? img : ''})`,
                  }}
                >
                  {isloading ? antIcon : null}
                  {!img ? <PictureOutlined /> : null}
                </span>
              </UploadPic>
            )}
          </div>

          {!isloading && img ? (
            <>
              <Tooltip
                placement="top"
                trigger="hover"
                mouseEnterDelay={2}
                title="预览"
              >
                <Button
                  className={s.view}
                  type="link"
                  size={'small'}
                  onClick={showView}
                  icon={<EyeOutlined />}
                />
              </Tooltip>
              <Tooltip
                placement="top"
                trigger="hover"
                mouseEnterDelay={2}
                title="删除"
              >
                <Button
                  type="link"
                  danger
                  size={'small'}
                  onClick={deleteImage}
                  icon={<DeleteOutlined />}
                />
              </Tooltip>
            </>
          ) : null}
        </Col>
      </Row>
      <Modal visible={viewImg} onCancel={hideView} title={wh} footer={null}>
        <div className={s.ref}>
          {img ? <img ref={ref} src={img} alt={''} /> : null}
        </div>
      </Modal>
      {!isloading && img ? <div className={s.imgtemp} ref={ref} /> : null}
    </>
  );
}
Example #3
Source File: TemplateInfoModal.tsx    From yugong with MIT License 4 votes vote down vote up
TemplateInfoModal: React.FC<Props> = ({ visible, onOk, onCancel }) => {
    const [tags, setTags] = useState<queryTagParams[]>([]);
    const pageData = useSelector((state: RootState) => state.pageData);
    const [defaultValue, setDefaultValue] = useState<AnyObject>();

    const [csrfToken] = useCookie('csrfToken')

    const getTags = useCallback(async () => {
        const tagsResult = await queryTag();
        setTags(tagsResult);
    }, []);

    useEffect(() => {
        const { template = {}, pageTitle } = pageData;
        const { title, cove, tag, describe, terminal, isPublic } = template;
        const defaultParams: TemplateInfo = {
            title: title || pageTitle,
            cove: !!cove ? [{thumbUrl: cove}] : [],
            tag: !!tag ? tag.split(',') : [],
            isPublic: (isPublic === 1),
            describe,
            terminal,
        };
        setDefaultValue(defaultParams);
        
    }, [pageData, pageData.template, visible]);

    useEffect(() => {
        getTags();
    }, [getTags]);

    const handleSubmit = useCallback(
        (data: AnyObject) => {
            if (!isType(data, 'Object')) return;
            data.describe = data.describe || '';
            if (onOk instanceof Function) onOk(data);
        },
        [onOk]
    );

    return (
        <Modal
            key={`${visible}`}
            title="模版信息"
            visible={visible}
            onCancel={onCancel}
            okText={'确定'}
            cancelText={'取消'}
            footer={null}
        >
            <Form
                name="templateInfo"
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 19 }}
                initialValues={defaultValue}
                onFinish={handleSubmit}
            >
                <Form.Item
                    label="模板标题"
                    name="title"
                    rules={[{ required: true, message: '请填写模板标题' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="终端"
                    name="terminal"
                    rules={[{ required: true, message: '请选择终端' }]}
                >
                    <Select placeholder="请选择">
                        <Select.Option value="mobile">移动端</Select.Option>
                        <Select.Option value="pc">PC端</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item
                    name="cove"
                    label="封面图片"
                    valuePropName="fileList"
                    getValueFromEvent={normFile}
                    extra="模版封面图片"
                    rules={[{ required: true, message: '请上传封面图片' }]}
                >
                    <Upload
                        action="/api/upload"
                        listType="picture"
                        maxCount={1}
                        headers={{
                          'x-csrf-token': csrfToken || ''
                        }}
                    >
                        <Button icon={<UploadOutlined />}>上传图片</Button>
                    </Upload>

                </Form.Item>
                <Form.Item label="描述" name="describe">
                    <Input.TextArea rows={3} />
                </Form.Item>
                <Form.Item
                    label="标签"
                    name="tag"
                    rules={[{ required: true, message: '请选择标签' }]}
                >
                    <Select mode="multiple" allowClear placeholder="标签">
                        {tags.map((item) => (
                            <Select.Option key={item.id} value={`${item.id}`}>
                                {item.name}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>

                <Form.Item
                    name="isPublic"
                    valuePropName="checked"
                    wrapperCol={{ offset: 9, span: 17 }}
                >
                    <Checkbox>发布为公共模板</Checkbox>
                </Form.Item>

                <Form.Item wrapperCol={{ offset: 10, span: 14 }}>
                    <Button type="primary" htmlType="submit">
                        确定
                    </Button>
                </Form.Item>
            </Form>
        </Modal>
    );
}