bprosic 6 Light Poster

Hi,
I have a form in React with few select/input components. Form doesnt get populated when user enters value in them.
Thats the case when I want for input "Username" -> when user starts writing here some username, then React - in Reducer ->
filters array of whole users in background. But then, input components doesnt get populated.

Here is code before render:

let [user, setUserState] = useState({
    username: '',
    email: '',
    firstname: '',
    languageselect: 0
});

let {
    username,
    email,
    firstname,
    languageselect
} = user;

const CheckExistingUserEmail = (parameters) => {
    const { filterby, keyword } = parameters;
    // dont send results to reducer, it will send also user object!! and return nothing
    let a =
      listOnlyUsernameEmail !== null
        ? usersExample.filter((h) => {
            const regex = new RegExp(`${keyword}`, 'gi');
            if (filterby === 'existing_username')
              return h.username.match(regex);
            else return h.email.match(regex);
          })
        : '';
    console.log(a);
  };
// event to populate form elements
const onChange = (e) => {
// works
if (e.target.name === 'languageselect') {
    setUserState({ ...user, id_lang: e.target.value });
    return;
}

if (e.target.name === 'username') {
    // execute filter to show us existing usernames in DB
    if (e.target.value !== '') {
    let parameters = {
        filterby: `existing_${e.target.name}`,
        keyword: e.target.value,
    };
    // Problem is here
    // Both functions do the same thing, filter existing array of data
    // when using local function, input elements gets populated what user is writing
    // when using reducer function, input element doesn't get populated, instead, whole form gets reseted
    // both functions work - they filter array. Only problem is that input doesnt get populated
    // Why?
    CheckExistingUserEmail(parameters); // here - local function | when using this, input is populated
    filterUsernameEmails(parameters); // reducer function | when using this, whole form gets reseted
    } else {
    clearFilterUsernamesEmail();
    }
    setUserState({ ...user, username: e.target.value }); // populate input field when user types sth
    return;
}
// works if not entered something in input username
setUserState({ ...user, [e.target.name]: e.target.value }); // populate the rest of fields in form
};

return {
(...)
<input
    type='text'
    className='px-3 py-3 placeholder-gray-500 text-gray-700 rounded text-sm shadow focus:outline-none focus:shadow-outline w-full ease-linear transition-all duration-150'
    name='username'
    value={username}
    autoComplete='off'
    onChange={(e) => onChange(e)}
/>
}

Code in state/reducer:

// in state
const filterUsernameEmails = (parameters2) => {
    dispatch({ type: FILTER_USERNAME_EMAIL, payload: parameters2 });
};

// in reducer
case FILTER_USERNAME_EMAIL: {
    switch (action.payload.filterby) {
    case 'existing_username':
        return {
        ...state,
        filteredUsernamesEmails: state.listOnlyUsernameEmail.filter((h) => {
            const regex = new RegExp(`${action.payload.keyword}`, 'gi');
            return h.username.match(regex);
        }),
        }; //*/
    case 'existing_email':
        return {
        ...state,
        filteredUsernamesEmails: state.listOnlyUsernameEmail.filter((h) => {
            const regex = new RegExp(`${action.payload.keyword}`, 'gi');
            return h.email.match(regex);
        }),
        };
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.