Heikkisorsa
Heikkisorsa

Reputation: 905

Show notification in a parser

I have a filter for phone numbers like here:

const UserFilter = (props: any) => <Filter {...props}>
    <TextInput label="Mobile" source="mobile" alwaysOn resettable parse={phoneParser} />
    <TextInput label="E-Mail" source="email" alwaysOn resettable />
</Filter>

And I use a parser in order to replace leading zeros with a fixed country code:

const phoneParser = (value: string) => {
    const needsCountryCode = value.charAt(0)=="0"
    if (needsCountryCode) {
        showNotification(`Mobile number reformatted with country code of Switzerland.`,'warning')
    }
    return needsCountryCode ? "+41"+value.substring(1):value;
};

Now, I wanted to notify the user everytime this replacement happens (usually only happens once). I tried to use the useNotify hook but it's not a functional component and then I tried the showNotification function, but it just doesn't do anything. Is this even possible in a parser function?

Upvotes: 0

Views: 94

Answers (1)

Gildas Garcia
Gildas Garcia

Reputation: 7066

I suggest you create a custom input for that. Something like this:

import { FieldTitle, InputHelperText, ResettableTextField, useNotify, useInput } from "react-admin";

const hasCountryCode = (value) => value.charAt(0) === "0";
const addCountryCode = (value) => "+41" + value.substring(1);

export const PhoneInput = (props) => {
    const { helperText, label, source, resource, ...restProps } = props;
    const {
      input: { name, onChange, ...rest },
      meta: { error, submitError, touched },
      isRequired,
    } = useInput(props);
    const notify = useNotify();

    const handleChange = (event) => {
        const value = event.target.value;
        if (hasCountryCode(value)) {
            onChange(value);
        } else {
            notify(
                `Mobile number reformatted with country code of Switzerland.`,
                { type: "warning" }
            );
            onChange(addCountryCode(value));
        }
    };
    
    return (
      <ResettableTextField
        name={name}
        onChange={handleChange}
        label={
          label !== "" &&
          label !== false && (
            <FieldTitle
              label={label}
              source={source}
              resource={resource}
              isRequired={isRequired}
            />
          )
        }
        error={!!(touched && (error || submitError))}
        helperText={
          <InputHelperText
            touched={touched}
            error={error || submitError}
            helperText={helperText}
          />
        }
        {...rest}
        {...restProps}
      />
    );
};

Upvotes: 2

Related Questions