medusajs / nextjs-starter-medusa

A performant frontend ecommerce starter template with Next.js 14 and Medusa.
https://next.medusajs.com/
MIT License
1.75k stars 487 forks source link

Country select field does not always get autofilled #176

Open SimonsThijs opened 1 year ago

SimonsThijs commented 1 year ago

Bug report

Describe the bug

The country select field does not always get autofilled while it should get autofilled. E.g., the shipping information at checkout should get automatically filled out if the user has a shipping address. This works for all fields but not for the country select field. It also happens when editing the billing address in the profile page.

Note that it does work in certain cases, e.g. when you refresh the page it seems to work. Its a strange bug and maybe someone with more React experience knows what the issue is.

System information

Storefront version: latest Node.js version: v20.5.1 Operating system: Irrelevant Browser (if relevant): At least Chrome and firefox

Steps to reproduce the behavior

First method

  1. Create a new user with a shipping address
  2. Go to the store and put something in your cart
  3. Go to checkout form
  4. All fields are filled out except for the country select field
  5. Refresh the page, now the country select is filled out

Second method

  1. Create a new user with a billing address
  2. Go to the store page
  3. Go back to the account page
  4. Go to profile tab in the account page
  5. Edit billing address
  6. All fields are filled out except for the country select field
  7. Refresh the page, now the country select is filled out

Expected behavior

Speaks for itself

Screenshots

Screenshot 2023-09-19 at 11 09 55

SimonsThijs commented 1 year ago

I found the issue. Countries get fetched from the backend. When the countries are not loaded yet, the option elements in the dom have not yet been constructed and thus can also not be selected.

Solution to this would be to set the defaultValues of a country select field only after the countries have been fetched.

I added this piece of code to the country select component:

    useEffect(() => {
      innerRef.current!.value = props.defaultValue as string
      if (props.defaultValue) {
        innerRef.current?.focus()
      }
    }, [countryOptions,])

Let me know if there is a better way to do this?