0

I used react-country-region-selector with useState, it worked well and updated the dropdown with my selection of country, code as follows:

import React, { useState } from 'react';

const App = () => {
  const [country, setCountry] = useState('');
  
  const handleCountryChange = (country) => {
    setCountry(country);
  }
  
  return (
    <CountryDropdown
        value={country}
        onChange={handleCountryChange}
        />
  )
}

Now I'm trying to use useReducer cause I have multiple states to update. However my code no longer works with react-country-region-selector, code as follows:

import React, { useReducer } from 'react';

const App = () => {

  const reducer = (state, action) => {
    switch (action.type) {
      case 'setCountry':
        return {
          country: state.country
        }
    }
  }
  
  const handleCountryChange = (country) => {
    dispatch({type: 'setCountry'});
  }
  
  return (
    <CountryDropdown
        value={country}
        onChange={handleCountryChange}
        />
  )

}

When selecting a country, the dropdown no longer updates. What is the matter with useReducer in this case? How can I update the country selection with useReducer?

one-hand-octopus
  • 2,229
  • 1
  • 17
  • 51

1 Answers1

0

You can read more detail about useReducer here: https://reactjs.org/docs/hooks-reference.html#usereducer

Your code should be:

import React, { useReducer } from 'react';

const App = () => {

    const reducer = (state, action) => {
        switch (action.type) {
            case 'setCountry':
                return {
                    ...state,
                    country: action.country
                }
        }
    }

    const [state, dispatch ]=  useReducer(reducer, {country: ''});

    const handleCountryChange = (country) => {
        dispatch({type: 'setCountry', country});
    }

    return (
        <CountryDropdown
            value={state.country}
            onChange={handleCountryChange}
        />
    )
}
Viet Dinh
  • 1,871
  • 1
  • 6
  • 18
  • Why return `country: action.country` rather than `country: state.country`? – one-hand-octopus Sep 08 '20 at 19:22
  • Cause argument state in function reducer is current state. It’s initialized at second param of function useReducer. When you want change state ( mean change country state ). You should return new state by assigned new country from data action. – Viet Dinh Sep 08 '20 at 19:25
  • If you see its helpful, please give vote to improve my reputation :)))) – Viet Dinh Sep 08 '20 at 19:29